C# GroupBy的基本使用教程
简介
GroupBy是LINQ查询中常用的操作,可以将序列按照一定的规则分组,返回一个以分组为键,子序列为值的字典。
基本使用
对于一个集合,我们可以使用GroupBy方法对其进行分组。以下是GroupBy方法的基本语法:
IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector
);
其中,参数keySelector用于规定分组规则,返回值类型为TKey;参数elementSelector用于返回每个分组的元素数目,返回值类型为TElement。
示例1:根据字符长度进行分组
string[] words = { "apple", "strawberry", "banana", "cherry", "peach" };
var groups = words.GroupBy(w => w.Length);
foreach (var group in groups)
{
Console.WriteLine("Words with {0} characters:", group.Key);
foreach (var word in group)
{
Console.WriteLine(word);
}
}
输出:
Words with 5 characters:
apple
Words with 10 characters:
strawberry
Words with 6 characters:
banana
cherry
Words with 5 characters:
peach
示例2:根据对象属性进行分组
我们创建一个Person类,该类包含属性Name和Age,然后创建一个Person集合,根据Age属性进行分组。
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person>
{
new Person { Name = "Tom", Age = 26 },
new Person { Name = "Jerry", Age = 28 },
new Person { Name = "Mike", Age = 26 },
new Person { Name = "Lisa", Age = 30 },
new Person { Name = "Nancy", Age = 28 },
};
var groups = people.GroupBy(p => p.Age);
foreach (var group in groups)
{
Console.WriteLine("People with age {0}:", group.Key);
foreach (var person in group)
{
Console.WriteLine(person.Name);
}
}
输出:
People with age 26:
Tom
Mike
People with age 28:
Jerry
Nancy
People with age 30:
Lisa
总结
GroupBy是LINQ查询中一个常用的操作,能够按照一定的规则对序列进行分组。我们可以使用LINQ语法或者方法调用的方式进行GroupBy操作,具体使用可以参考上述示例。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C# GroupBy的基本使用教程 - Python技术站