对于C#中的GroupBy
方法,可以通过foreach
循环来遍历每个分组,并对每个分组中的元素进行操作。以下是一些常用的分组遍历操作技巧:
foreach
循环遍历每个分组,并对每个分组中的元素进行操作:var groups = list.GroupBy(item => item.Key);
foreach(var group in groups)
{
Console.WriteLine($"Key: {group.Key}");
foreach(var item in group)
{
Console.WriteLine($"Item: {item.Value}");
}
}
var groups = list.GroupBy(item => item.Key);
groups.ToList().ForEach(group =>
{
Console.WriteLine($"Key: {group.Key}");
group.ToList().ForEach(item =>
{
Console.WriteLine($"Item: {item.Value}");
});
});
SelectMany
方法将所有分组中的元素合并成一个序列,并对每个元素进行操作:var groups = list.GroupBy(item => item.Key);
var allItems = groups.SelectMany(group => group);
foreach(var item in allItems)
{
Console.WriteLine($"Item: {item.Value}");
}
Aggregate
方法对每个分组中的元素进行累加操作:var groups = list.GroupBy(item => item.Key);
var sum = groups.Select(group => group.Sum(item => item.Value)).Aggregate((acc, next) => acc + next);
Console.WriteLine($"Sum: {sum}");