溫馨提示×

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

c#
小樊
207
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女