2014-08-31 42 views
-2

好的Linq'ers。試試這個。Linq fluent vs Linq在布爾值上選擇

爲什麼會

NextActioners.Select(n => n.NextActioner.Equals(true)); 

正確找到2條記錄,

正確找到沒有?

在我good'ol Linqpad:

public class AppPerson 
     { 
      public string PersonId; 
      public string FullName; 
      public string Role; 
      public bool NextActioner; 
     } 

    void Main() 
    { 
     var NextActioners = new List<AppPerson> { 
        new AppPerson{FullName="testFullname1", NextActioner=false}, 
        new AppPerson{FullName="testFullname2", NextActioner=false}, 
       }; 

     //Are all the NextActioners 'nextActioner' value false 
     var noApproversSelected = NextActioners.All(a => a.NextActioner.Equals(false)); 
     Console.WriteLine("noApproversSelected={0}",noApproversSelected.ToString());//Result = true 

     var listOfApprovers = from a in NextActioners 
         where (a.NextActioner.Equals(true)) 
         select a; 
     Console.WriteLine("listOfApprovers.Count()={0}",listOfApprovers.Count().ToString());//Result = 0 

     var listOfApprovers1 = NextActioners.Select(n => n.NextActioner.Equals(true)); 
     Console.WriteLine("listOfApprovers1.Count()={0}",listOfApprovers1.Count().ToString());//Result = 2!!!!!!! 

     var listOfApprovers2 = NextActioners.Select(n => n.NextActioner == true); 
     Console.WriteLine("listOfApprovers2.Count()={0}",listOfApprovers2.Count().ToString());//Result = 2!!!!!!! 

     var listOfApprovers3 = NextActioners.Select(n => n.NextActioner); 
     Console.WriteLine("listOfApprovers3.Count()={0}",listOfApprovers3.Count().ToString());//Result = 2!!!!!!! 

    } 
+3

因爲您將每個操作者都投影到該列表中,而不是過濾。那應該是一個'Where()'調用。 – 2014-08-31 06:36:27

+1

你能解釋爲什麼你相信這兩個查詢應該做同樣的事情嗎?我很想知道爲什麼人們相信LINQ的錯誤。 – 2014-08-31 06:54:39

回答

6

通過使用

NextActioners.Select(n => n.NextActioner.Equals(true)); 

你是不是做任何過濾。選擇運算符僅將一種類型的結果轉換爲另一種類型的結果。爲了過濾結果,您需要使用Where操作符,如下所示:

var listOfApprovers1 = NextActioners.Where(n => n.NextActioner.Equals(true)).Select(n=>n); 
+7

'.Select(n => n)'是毫無意義的。 – MarcinJuraszek 2014-08-31 06:39:28

+0

@CarstenKönig我認爲,如果你的迭代器有這些副作用,你就有更大的問題開始:) – Noctis 2014-08-31 10:28:57

+0

@CarstenKönig可能是真的,但看到別人粗魯,並不意味着粗魯無禮...... :) – Noctis 2014-08-31 10:44:06