嵌套排序组与计数

时间:2015-03-06 17:31:23

标签: c# linq

我正在试图弄清楚如何获取一个列表并获得一个组列表,每个组列表包含总金额的分组。我能够完成第一个goup,并且查看了使用LINQ做嵌套组,但是不确定如何使用我需要的信息。贝娄是一个样本列表和我目前的编码。

样本列表

var list = new[] {
    new { Product = "Product1", Category = "Category1", Issue = "Issue1" },
    new { Product = "Product1", Category = "Category1", Issue = "Issue2" },
    new { Product = "Product2", Category = "Category2", Issue = "Issue1" },
    new { Product = "Product3", Category = "Category1", Issue = "Issue2" },
    new { Product = "Product2", Category = "Category2", Issue = "Issue1" },
    new { Product = "Product1", Category = "Category1", Issue = "Issue" },
}.ToList()

示例代码

var topIssues = from issue in storage.Issues
                group issue by new {issue.Category, issue.Issue} into issueGroup
                let count = issueGroup.Count()
                orderby count descending
                select new { Issue = issueGroup.Key, Count = count};

我正在做一个由Category和Issue定义的组,然后我需要每个组中的项目数,并且列表按此顺序按降序排序。但是,我希望在这些产品中包含一个组,其中还包含每个产品的项目数也按降序排列。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

var topIssues = (from issue in list
                group issue by new {issue.Category, issue.Issue}
                into issueGroup
                select new
                {
                    Issue = issueGroup.Key, 
                    Count = issueGroup.Count(),
                    GP = (from i in issueGroup group i by i.Product into gp select new
                    {
                        Product = gp.Key, Count = gp.Count()
                    }).OrderByDescending(g=>g.Count)
                }).OrderByDescending(d=>d.Count);