c# groupby的分組轉(zhuǎn)換操作技巧有哪些

c#
小樊
91
2024-08-10 03:48:43

一些c# groupby的分組轉(zhuǎn)換操作技巧包括:

  1. 使用Select方法對(duì)每個(gè)分組進(jìn)行轉(zhuǎn)換操作,例如:
var groupedData = data.GroupBy(x => x.Category)
                      .Select(g => new
                      {
                          Category = g.Key,
                          Count = g.Count(),
                          TotalValue = g.Sum(x => x.Value)
                      });
  1. 使用SelectMany方法將所有分組合并為一個(gè)集合,然后進(jìn)行轉(zhuǎn)換操作,例如:
var transformedData = data.GroupBy(x => x.Category)
                          .SelectMany(g => g.Select(x => new
                          {
                              Category = g.Key,
                              Value = x.Value * 2
                          }));
  1. 使用ToDictionary方法將分組轉(zhuǎn)換為字典,方便后續(xù)操作,例如:
var groupedDictionary = data.GroupBy(x => x.Category)
                            .ToDictionary(g => g.Key, g => g.ToList());
  1. 使用Aggregate方法對(duì)每個(gè)分組進(jìn)行累加操作,例如:
var aggregatedData = data.GroupBy(x => x.Category)
                         .Select(g => new
                         {
                             Category = g.Key,
                             TotalValue = g.Aggregate(0.0, (acc, x) => acc + x.Value)
                         });

0