在C#中,可以使用LINQ的GroupBy方法來對集合進行分組聚合操作。以下是一些常用的分組聚合操作技巧:
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)
});
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)
});
var groupedData = data.GroupBy(x => x.Key)
.ToDictionary(group => group.Key, group => group.ToList());
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方法的分組聚合操作技巧,可以根據具體的需求進行相應的調整和擴展。