LINQ 学习路程 -- 查询操作 GroupBy ToLookUp
生活随笔
收集整理的這篇文章主要介紹了
LINQ 学习路程 -- 查询操作 GroupBy ToLookUp
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
| Grouping Operators | Description |
|---|---|
| GroupBy | GroupBy操作返回根據(jù)一些鍵值進(jìn)行分組,每組代表IGrouping<TKey,TElement>對(duì)象 |
| ToLookup | ToLookup is the same as GroupBy; the only difference is the execution of GroupBy is deferred whereas ToLookup execution is immediate. |
?
?
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,new Student() { StudentID = 2, StudentName = "Steve", Age = 21 } ,new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,new Student() { StudentID = 5, StudentName = "Abram" , Age = 21 } };var groupedResult = from s in studentListgroup s by s.Age;//iterate each group foreach (var ageGroup in groupedResult) {Console.WriteLine("Age Group: {0}", ageGroup .Key); //Each group has a key foreach(Student s in ageGroup) // Each group has inner collectionConsole.WriteLine("Student Name: {0}", s.StudentName); }
?
?可以使用foreach遍歷group,每個(gè)Group包含一個(gè)key和內(nèi)部的集合
?
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,new Student() { StudentID = 2, StudentName = "Steve", Age = 21 } ,new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,new Student() { StudentID = 5, StudentName = "Abram" , Age = 21 } };var groupedResult = studentList.GroupBy(s => s.Age);foreach (var ageGroup in groupedResult) {Console.WriteLine("Age Group: {0}", ageGroup.Key); //Each group has a key foreach(Student s in ageGroup) //Each group has a inner collection Console.WriteLine("Student Name: {0}", s.StudentName); }
?
ToLookup和GroupBy一樣,唯一不同的是GroupBy是延遲執(zhí)行,而ToLookup是立即執(zhí)行?
?
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,new Student() { StudentID = 2, StudentName = "Steve", Age = 21 } ,new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,new Student() { StudentID = 5, StudentName = "Abram" , Age = 21 } };var lookupResult = studentList.ToLookup(s => s.age);foreach (var group in lookupResult) {Console.WriteLine("Age Group: {0}", group.Key); //Each group has a key foreach(Student s in group) //Each group has a inner collection Console.WriteLine("Student Name: {0}", s.StudentName); }
?
?
注意:GroupBy和ToLookup返回一個(gè)集合(包含key,根據(jù)key分組的內(nèi)部集合)
?
轉(zhuǎn)載于:https://www.cnblogs.com/lanpingwang/p/6602449.html
總結(jié)
以上是生活随笔為你收集整理的LINQ 学习路程 -- 查询操作 GroupBy ToLookUp的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阳痿治疗多少钱啊?
- 下一篇: 对大学生学习Linux系统的七项实用建议