对于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}"); }}使用LINQ方法链对每个分组中的元素进行操作: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}");