簡體   English   中英

LINQ中的group by子句

[英]group by clause in LINQ

我已經通過以下代碼,但不明白組子句如何進行分組

請幫忙。 我是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是如何生成的。 提前致謝 。

分組是指將數據分組的操作,以便每組中的元素共享一個共同的屬性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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM