c# groupby的分组聚合操作技巧有哪些

655Z技术栈 C#编程 2025年06月23日 10

在C#中,可以使用LINQ的GroupBy方法来对集合进行分组聚合操作。以下是一些常用的分组聚合操作技巧:

  1. 使用GroupBy方法按照指定的键对集合进行分组,然后使用Select方法对每个分组进行聚合操作。
var groupedData = data.GroupBy(x => x.Key) .Select(group => new { Key = group.Key, Count = group.Count(), Sum = group.Sum(x => x.Value), Avg = group.Average(x => x.Value) });
  1. 使用GroupBy方法按照多个键对集合进行分组,然后使用Select方法对每个分组进行聚合操作。
var groupedData = data.GroupBy(x => new { x.Key1, x.Key2 }) .Select(group => new { Key1 = group.Key.Key1, Key2 = group.Key.Key2, Count = group.Count(), Sum = group.Sum(x => x.Value), Avg = group.Average(x => x.Value) });
  1. 使用GroupBy方法按照键对集合进行分组,并使用ToDictionary方法将分组结果转换为字典。
var groupedData = data.GroupBy(x => x.Key) .ToDictionary(group => group.Key, group => group.ToList());
  1. 使用GroupBy方法按照键对集合进行分组,然后使用Aggregate方法对每个分组进行进一步的聚合操作。
var groupedData = data.GroupBy(x => x.Key) .Select(group => new { Key = group.Key, MaxValue = group.Max(x => x.Value), MinValue = group.Min(x => x.Value), ConcatenatedValues = group.Aggregate("", (acc, x) => acc + x.Value.ToString() + ",") });

以上是一些常用的C#中GroupBy方法的分组聚合操作技巧,可以根据具体的需求进行相应的调整和扩展。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”