当需要对查询结果进行分组时,我们可以使用LINQ中的分组操作符。常用的分组操作符有GroupBy
、ToLookup
等。
GroupBy操作符
GroupBy
操作符将一个序列按照指定条件分成多个组,并返回每个组及其对应的元素集合。其语法为:
IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
其中,source
表示需要进行分组的序列,keySelector
代表牵头分组的键选择器。
以下是一个使用GroupBy
操作符的示例:
var students = new List<Student>
{
new Student { Name = "Tony", Grade = 3.2, Gender = "M" },
new Student { Name = "Grace", Grade = 3.8, Gender = "F" },
new Student { Name = "Tom", Grade = 2.9, Gender = "M" },
new Student { Name = "Jerry", Grade = 3.5, Gender = "M" },
new Student { Name = "Sandy", Grade = 3.7, Gender = "F" }
};
var groups = students.GroupBy(s => s.Gender);
foreach (var group in groups)
{
Console.WriteLine("Gender: {0}", group.Key);
foreach (var student in group)
{
Console.WriteLine(" Name: {0}, Grade: {1}", student.Name, student.Grade);
}
}
输出:
Gender: M
Name: Tony, Grade: 3.2
Name: Tom, Grade: 2.9
Name: Jerry, Grade: 3.5
Gender: F
Name: Grace, Grade: 3.8
Name: Sandy, Grade: 3.7
在该示例中,我们将学生按照性别进行分组,并输出每个性别对应的学生及其信息。
ToLookup操作符
ToLookup
操作符也可以对一个序列进行分组,不同的是,它返回的是一个ILookup
集合。与GroupBy
不同的是,当分组完成后,可以通过ILookup
集合根据键查找到对应的元素集合。其语法为:
ILookup<TKey, TSource> ToLookup<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
以下是一个使用ToLookup
操作符的示例:
var students = new List<Student>
{
new Student { Name = "Tony", Grade = 3.2, Gender = "M" },
new Student { Name = "Grace", Grade = 3.8, Gender = "F" },
new Student { Name = "Tom", Grade = 2.9, Gender = "M" },
new Student { Name = "Jerry", Grade = 3.5, Gender = "M" },
new Student { Name = "Sandy", Grade = 3.7, Gender = "F" }
};
var groups = students.ToLookup(s => s.Gender);
var maleStudents = groups["M"];
foreach (var student in maleStudents)
{
Console.WriteLine("Name: {0}, Grade: {1}", student.Name, student.Grade);
}
输出如下:
Name: Tony, Grade: 3.2
Name: Tom, Grade: 2.9
Name: Jerry, Grade: 3.5
在该示例中,我们同样将学生按照性别进行分组,不同的是我们使用ToLookup
操作符,并查询男生的信息。
总之,使用分组操作符可以使我们更加灵活的对数据进行查询和统计,是LINQ中的重要内容之一。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:linq中的分组操作符 - Python技术站