【问题标题】:how to group by multiple columns using linq [duplicate]如何使用linq按多列分组[重复]
【发布时间】:2014-01-23 01:24:28
【问题描述】:

我有一个数据库表,其中包含如下多行数据的数据集

ItemId               Code                             StatusId
-------------------- ---------------------------------------------
62224                NC0860000                             8
62225                NC0860000                             8
62226                NC0860000                             8
62227                NC0860200                             5
62228                NC0860000                             5
62229                NC0860000                             5
62230                NC0860000                             5

我想要完成的是输出结果为

NC0860000  8  3  (code, status, count)
NC0860000  5  3

我不完全理解 EF 中分组的工作原理。我可以使用以下查询获取单个组的键和计数:

var results = (from ssi in ctx.StageSubmitItems
                           join s in ctx.StageSubmissions on ssi.SubmissionId equals s.SubmissionId
                           where s.ContributorCode == contributorId
                           group ssi.SubmitItemId by ssi.AgencyCode into g
                           select new {AgencyCode = g.Key, Count = g.Count() }).ToList();

但我不知道如何按代码分组,然后按 StatusId 分组,然后按状态生成总行数。

如果有任何关于在哪里查看如何完成此操作或我在查询中做错了什么的建议,我将不胜感激。

【问题讨论】:

    标签: linq entity-framework linq-to-sql


    【解决方案1】:

    您可以按如下方式按新的匿名类分组:

    // I created a Foo class to show this working
    var fooList = new List<Foo> {
        new Foo { ItemId = 62224, Code = "NC0860000", StatusId = 8 },
        new Foo { ItemId = 62225, Code = "NC0860000", StatusId = 8 },
        new Foo { ItemId = 62226, Code = "NC0860000", StatusId = 8 },
        new Foo { ItemId = 62227, Code = "NC0860200", StatusId = 5 },
        new Foo { ItemId = 62228, Code = "NC0860000", StatusId = 5 },
        new Foo { ItemId = 62229, Code = "NC0860000", StatusId = 5 },
        new Foo { ItemId = 62230, Code = "NC0860000", StatusId = 5 },
    };
    
    var results = (from ssi in fooList
        // here I choose each field I want to group by
        group ssi by new { ssi.Code, ssi.StatusId } into g
        select new { AgencyCode = g.Key.Code, Status = g.Key.StatusId, Count = g.Count() }
    ).ToList();
    
    // LINQPad output command
    results.Dump();
    

    根据提供的数据,这里是输出:

    AgencyCode Status Count
    NC0860000  8      3 
    NC0860200  5      1 
    NC0860000  5      3 
    

    我猜“NC0860200”是一个错误,但它在您的示例数据中,所以我将其包含在内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2023-03-10
      • 1970-01-01
      • 2016-12-10
      • 2021-11-22
      • 1970-01-01
      相关资源
      最近更新 更多