2017-06-14 50 views
0

我有以下的代码示例:LINQ检查什么条件多和条件返回false

List<string> temp = new List<string>(); 
temp.Add("bla bla"); 
temp.Add("111"); 
temp.Add("222"); 
temp.Add("1111111"); 
temp.Where(x => x.Length <= 5 && x.Contains("1")).ToList(); 

我期待的结果是:

元素:

[0] - “BLA BLA “ - 导致假 - 坠毁条件长度< = 5

[1] - ”111“ - 结果真

[2] - “222” - 导致假 - 坠毁条件x.Contains( “1”)

[3] - “1111111” - 导致假 - 坠毁条件长度< = 5

我能以某种方式做到吗?

+0

因此,而不是过滤,你想得到所有的元素与一个额外的领域提及真/假和理由? –

回答

1

通过在单独列表中分割标准(如Func<string,bool s),您可以测试每个单独的设置。一步,通过缠绕它们作为Expression<>中,(失败)绕圈的内容可以得到:

List<string> temp = new List<string>{"bla bla", "111","222","1111111"}; 

var criteria = new Expression<Func<string,bool>>[]{x => x.Length <= 5 , x => x.Contains("1")} 
    .Select(c=>new{Test=c.Compile(), Name = c.ToString()}).ToList(); //get precompiled lambdas with their names, based on the lambda expressions 

var results = from s in temp  
    let fail = criteria.FirstOrDefault(c=>!c.Test(s)) //get the first criterium to fail (if any) 
    select new {Value = s, Result = fail ==null , FailedOn = fail?.Name}; 


foreach(var m in results) //test output 
    Console.WriteLine("Value: {0} [{1}] {2}" , m.Value, m.Result, m.Result ? null : " crashed on " + m.FailedOn); 

以上的结果:

  • 值:血乳酸血乳酸[FALSE]坠毁X =>(x.Length < = 5)
  • 值:111 [TRUE]
  • 值:222 [FALSE]坠毁在X => x.Contains( “1”)
  • 值:1111111 [假]在x =>(x.Len gth < = 5)
+0

谢谢!这是我需要的 –

0

当我检查你的代码是否正确执行,并给予正确的结果

List<string> temp = new List<string>(); 
      temp.Add("bla bla"); 
      temp.Add("111"); 
      temp.Add("222"); 
      temp.Add("1111111"); 
      var result= temp.Where(x => x.Length <= 5 && x.Contains("1")).ToList(); 

      foreach(var item in result) 
      { 
       Console.WriteLine("x={0}", item); 
      } 

enter image description here

如果你想返回true,而不是你可以使用的东西,如: VAR RESULT1 = temp.Where (x => x.Length < = 5 & & x.Contains(“1”))。Select(x => true).ToList();