【问题标题】:C# Grouping in LINQ with sum of certain fieldsC# 在 LINQ 中使用某些字段的总和进行分组
【发布时间】:2017-10-30 14:42:50
【问题描述】:

我有多个文档,它们的字段大多相同。唯一不同的两个字段是PriceQuantity。我想创建一个IEnumerable(),其中包含与每个分组匹配的第一个项目,但价格和数量字段替换为取自该分组中所有其他匹配项目的sum()

fieldone   fieldtwo   fieldthree   price   quantity
a1         b1         c1           3       5
a1         b1         c1           13      15
a1         b1         c1           23      25
a2         b2         c2           4       7
a2         b2         c2           14      17

应该返回:

fieldone   fieldtwo   fieldthree   price   quantity
a1         b1         c1           39      45
a2         b2         c2           18      24

我一直在看GroupBy() 例如:

var groupedResults = results.GroupBy(a => new { 
    a.Item1.FieldOne, 
    a.Item1.FieldTwo, 
    a.Item2.FieldThree}
)

但我不知道如何使用它来获得我想要的结果。

【问题讨论】:

标签: c# linq


【解决方案1】:

您需要将您的组投影出来以汇总必填字段

var groupedResults = results.GroupBy(a => new { 
    a.Item1.FieldOne, 
    a.Item1.FieldTwo, 
    a.Item2.FieldThree}
).Select(g => new {
    g.Key.FieldOne,
    g.Key.FieldTwo,
    g.Key.FieldThree,
    Price = g.Sum(x => x.Price),
    Quantity = g.Sum(x => x.Quantity)
});

还有另一个重载,您可以为结果提供第二个参数GroupBy,这样可以节省在GroupBy 之后链接第二个Select,但我个人更喜欢上面的这种方法。

【讨论】:

    【解决方案2】:

    您需要使用包含结果选择器的重载。

    var groupedResults = results.GroupBy(a => new 
    { 
        a.Item1.FieldOne, 
        a.Item1.FieldTwo, 
        a.Item2.FieldThree
    }, 
    (key, items) => new 
    { 
        key.FieldOne,
        key.FieldTwo,
        key.FieldThree,
        Price = items.Sum(a => a.Price), 
        Quantity = items.Sum(a => a.Quantity) 
    });
    

    【讨论】:

      【解决方案3】:

      你可以测试一下:

      var result = Db.Entity
             .GroupBy(p=>new {x.fieldone, x.fiedltwo, x.fieldthree})
             .Select(p=> new { 
                   fieldone = p.fieldone, 
                   fieldtwo = p.fiedltwo, 
                   fieldthree = p.fieldthree, 
                   price = p.Sum(x=>x.price), 
                   quantity = p.Sum(x=>x.quantity)}).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-24
        • 1970-01-01
        • 2018-04-25
        相关资源
        最近更新 更多