對于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}");