GroupBy Expression
本文关键字:Expression GroupBy | 更新日期: 2023-09-27 18:02:21
我有以下对象,我想有一个结果,提供一个对象集合,按第一个类别描述分组,然后按子类别描述分组:
类别(计数),,,,子类别(计数)
,,,,子类别(计数)
public class Posting
{
public Category Category { get; set; }
public SubCategory SubCategory { get; set; }
}
public class Category
{
public string Description { get; set; }
}
public class SubCategory
{
public string Description { get; set; }
}
编辑
所以我让它像这样工作:
foreach (var category in col.GroupBy(x => x.Category.Description).Select(x => new { CategoryName = x.Key, Items = x }).OrderBy(x => x.CategoryName))
{
Console.WriteLine(category.CategoryName);
foreach (var subCategory in category.Items.GroupBy(x => x.SubCategory.Description).Select(x => new { SubCategoryName = x.Key }).OrderBy(x => x.SubCategoryName))
{
Console.WriteLine("'t" + subCategory.SubCategoryName);
}
}
但我想把它变成一个对象图,这可能吗?
这看起来非常接近,需要注意的是,"内部"子类别分组的Key
字段是一个包含类别和子类别的匿名类型。但是,根据你的应用程序在做什么,这可能是一个功能,因为你总是有可用的类别。
var results = col
.GroupBy(posting => new
{
Category = posting.Category.Description,
SubCategory = posting.SubCategory.Description
})
.GroupBy(group => group.Key.Category.Description);