在C#中,可以使用GroupBy方法來將一個集合按照指定的條件進行分組。在進行分組嵌套操作時,可以使用SelectMany方法來對每個分組進行進一步的操作。以下是幾種常用的分組嵌套操作技巧:
var nestedGroups = data.GroupBy(x => x.Category)
.SelectMany(group => group);
var nestedGroups = data.GroupBy(x => x.Category)
.Select(group => new
{
Category = group.Key,
SubGroups = group.GroupBy(x => x.SubCategory)
});
var aggregatedGroups = data.GroupBy(x => x.Category)
.Select(group => new
{
Category = group.Key,
Count = group.Count(),
Total = group.Sum(x => x.Value)
});
var filteredGroups = data.GroupBy(x => x.Category)
.Select(group => new
{
Category = group.Key,
Items = group.Where(x => x.Value > 0)
});
這些技巧可以幫助我們更靈活地對分組結果進行操作,實現更復雜的數據處理需求。