简体   繁体   English

分组表达

[英]GroupBy Expression

I have the following object(s) and I want to have a result that provides a collection of objects grouped by first category description and then grouped by subcategory description with: 我有以下对象,并且想要得到一个结果,该结果提供按第一类别描述分组然后按子类别描述分组的对象集合:

Category(Count) 类别(计数)
SubCategory(Count) 子类别(计数)
SubCategory(Count) 子类别(计数)

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; }
}

EDIT 编辑

So I have this working like so: 所以我有这样的工作:

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);
                }
            }

But I would like to get this into one object graph, is that possible? 但是我想将其整合到一个对象图中,这可能吗?

This seems to be pretty close, with the caveat that the Key field of the "inner" sub-category groupings is an anonymous type containing both the Category and SubCategory. 需要注意的是,“内部”子类别分组的“ Key字段是同时包含“类别”和“子类别”的匿名类型,这似乎很接近。 But, depending on what your application is doing, that might be a feature since you'll always have the Category available. 但是,取决于您的应用程序在做什么,这可能是一项功能,因为您将始终拥有“类别”。

var results = col
    .GroupBy(posting => new
        {
            Category = posting.Category.Description,
            SubCategory = posting.SubCategory.Description
        })
    .GroupBy(group => group.Key.Category.Description);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM