2013-10-14 225 views
0

我已經通過了下面的代碼,但不明白group子句是如何分組的LINQ中的group by子句

請幫忙。我是c#的新手。

public static List<Student> GetStudents() 
     { 
      // Use a collection initializer to create the data source. Note that each element 
      // in the list contains an inner sequence of scores. 
      List<Student> students = new List<Student> 
     { 
      new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 72, 81, 60}}, 
      new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}}, 
      new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {99, 89, 91, 95}}, 
      new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {72, 81, 65, 84}}, 
      new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {97, 89, 85, 82}} 
     }; 

      return students; 

     } 
List<Student> students = GetStudents(); 

      // Write the query. 
      var studentQuery = 
       from student in students 
       let avg = (int)student.Scores.Average() 
       group student by (avg == 0 ? 0 : avg/10); 

我不明白StudentQuery是如何生成的。 在此先感謝。

+1

這**不是**的問題**一個新的學習者**必須關心,我敢肯定,許多'LINQ用戶'只是知道**如何使用它**即使沒有注意到**它是如何實現的**,學習像這樣的東西會減慢你的速度**。它類似於**當你學習WPF時,你總是在想它如何呈現3D視覺**。當然,它應該被關心,但這是一個**高級**話題,根本不適用於學習者。 –

+0

感謝國王。很長一段時間後,我得到了一個非常好的建議。我來自c + +背景,我已經幾天前開始c#。你能告訴我我應該繼續哪種方式嗎?我也想去參加微軟認證。請幫忙。 – Kenta

回答

1

分組是指將數據放入組中,以便每組中的元素共享一個共同屬性。GroupBy將學生分成組 - 平均分爲0-9,10-19,20-29,30- 39等你應該看看 http://msdn.microsoft.com/en-us//library/bb546139.aspx

ps

group student by (avg == 0 ? 0 : avg/10); 

似乎對我來說過分。你可以簡單地改變它

group student by (avg/10); 

pps:我更喜歡其他風格的LINQ,但它完全是個人選擇。其他風格將是

var studentQuery = students.GroupBy(x => x.Scores.Average()/10); 
+0

它更適合lambda。 :) – Kenta