在C#中使用GroupBy進行分組統計操作時,可以結合LINQ查詢語句來實現各種統計需求。以下是一些常見的操作技巧:
var groupedData = data.GroupBy(x => x.Category)
.Select(g => new { Category = g.Key, Count = g.Count() });
var groupedData = data.GroupBy(x => x.Category)
.Select(g => new { Category = g.Key, Sum = g.Sum(x => x.Value) });
var groupedData = data.GroupBy(x => x.Category)
.Select(g => new { Category = g.Key, Average = g.Average(x => x.Value) });
var groupedData = data.GroupBy(x => x.Category)
.Select(g => new { Category = g.Key, MaxValue = g.Max(x => x.Value), MinValue = g.Min(x => x.Value) });
var groupedData = data.GroupBy(x => x.Category)
.Select(g => new {
Category = g.Key,
Count = g.Count(),
Sum = g.Sum(x => x.Value),
Average = g.Average(x => x.Value),
MaxValue = g.Max(x => x.Value),
MinValue = g.Min(x => x.Value)
});
通過以上技巧,可以靈活地對分組后的數據進行各種統計操作,滿足不同的業務需求。