Grouping Operators | Description |
---|---|
GroupBy | GroupBy操作返回根据一些键值进行分组,每组代表IGrouping<TKey,TElement>对象 |
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 = , StudentName = "John", Age = } ,
new Student() { StudentID = , StudentName = "Steve", Age = } ,
new Student() { StudentID = , StudentName = "Bill", Age = } ,
new Student() { StudentID = , StudentName = "Ram" , Age = } ,
new Student() { StudentID = , StudentName = "Abram" , Age = }
}; var groupedResult = from s in studentList
group 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 collection
Console.WriteLine("Student Name: {0}", s.StudentName);
}
可以使用foreach遍历group,每个Group包含一个key和内部的集合
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = , StudentName = "John", Age = } ,
new Student() { StudentID = , StudentName = "Steve", Age = } ,
new Student() { StudentID = , StudentName = "Bill", Age = } ,
new Student() { StudentID = , StudentName = "Ram" , Age = } ,
new Student() { StudentID = , StudentName = "Abram" , Age = }
}; 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是延迟执行,而ToLookup是立即执行
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = , StudentName = "John", Age = } ,
new Student() { StudentID = , StudentName = "Steve", Age = } ,
new Student() { StudentID = , StudentName = "Bill", Age = } ,
new Student() { StudentID = , StudentName = "Ram" , Age = } ,
new Student() { StudentID = , StudentName = "Abram" , Age = }
}; 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返回一个集合(包含key,根据key分组的内部集合)