2017-06-14 43 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();