根据指定的键选择器函数对序列中的元素进行分组。
命名空间: System.Linq
程序集: System.Core(在 System.Core.dll 中)
public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector )
类型参数
- TSource
-
中的元素的类型。
- TKey
-
表示的函数返回的键类型。
参数
- source
- 类型:System.Linq.IQueryable<TSource>
IQueryable<T>。
- keySelector
- 类型:System.Linq.Expressions.Expression<Func<TSource, TKey>>
用于提取每个元素的键的函数。
使用说明
在 Visual Basic 和 C# 中,可以在 IQueryable<TSource> 类型的任何对象上将此方法作为实例方法来调用。当使用实例方法语法调用此方法时,请省略第一个参数。有关更多信息,请参见扩展方法 (Visual Basic)或扩展方法(C# 编程指南)。| 异常 | 条件 |
|---|---|
| ArgumentNullException |
null。 |
对序列中的元素进行分组。
class Pet { public string Name { get; set; } public int Age { get; set; } } public static void GroupByEx1() { // Create a list of Pet objects. List<Pet> pets = new List<Pet>{ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 }, new Pet { Name="Daisy", Age=4 } }; // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. var query = pets.AsQueryable().GroupBy(pet => pet.Age); // Iterate over each IGrouping in the collection. foreach (var ageGroup in query) { Console.WriteLine("Age group: {0} Number of pets: {1}", ageGroup.Key, ageGroup.Count()); } } /* This code produces the following output: Age group: 8 Number of pets: 1 Age group: 4 Number of pets: 2 Age group: 1 Number of pets: 1 */