按 LINQ 分组与按 SQL 分组

詹尼斯 S。

我在 SQL 中有以下查询,我想将其转换为 LINQ 语句。

select AreaId, BrandId, MilestoneId, DocumentCategoryId
from Document
group by AreaId, Brandid, MilestoneId, DocumentCategoryId

我试过,例如,

var docs =
    from d in documents
    group d by new
    {
        d.Area,
        d.Brand,
        d.MilestoneId,
        d.DocumentCategoryId
    } into gcs
    select new Group()
    {
        Area = gcs.Key.Area,
        Brand = gcs.Key.Brand,
        MilestoneId = gcs.Key.MilestoneId,
        DocumentCategoryId = gcs.Key.DocumentCategoryId,
    };

var docs = documents
    .GroupBy(d => new Group
    {
        Area = d.Area,
        Brand = d.Brand,
        MilestoneId = d.MilestoneId,
        DocumentCategoryId = d.DocumentCategoryId,
    })

但 SQL 中的结果返回 88 行(目标),查询语法中返回 78 行,LINQ 中返回 270 行(总数)。

我想要一个 LINQ 语句来返回 88 行。

马克·格拉维尔

我希望最终版本本质上是切换到 LINQ-to-Objects - 即每行填充一个Group 对象,然后在 .NET 术语中分组,这意味着每组一行,因为我怀疑您Group实现了正确的平等模式。为了让 LINQ 正确处理上一个版本,您可能需要在混合中添加一个匿名类型(LINQ 理解这应该像元组一样):

var docs = documents
    .GroupBy(d => new
    {
        Area = d.Area,
        Brand = d.Brand,
        MilestoneId = d.MilestoneId,
        DocumentCategoryId = d.DocumentCategoryId,
    }).Select(grp => new Group {
        Area = grp.Key.Area,
        Brand = grp.Key.Brand,
        MilestoneId = grp.Key.MilestoneId,
        DocumentCategoryId = grp.Key.DocumentCategoryId,
    });

至于88 vs 78:你有没有看下发出的是什么SQL?那应该告诉你它在做什么不同。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章