温馨提示×

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

c#
小樊
101
2024-08-10 03:43:38
栏目: 编程语言

在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方法的分组聚合操作技巧,可以根据具体的需求进行相应的调整和扩展。

0