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