【问题标题】:Eliminate duplicates in the List and sum up the quantity field消除List中的重复并总结数量字段
【发布时间】:2020-05-21 07:19:52
【问题描述】:

我有一个由 ID 和数量组成的列表。 ID 以不同的数量重复。我想删除重复的 ID 并添加数量。 例如:ID1:4 ID2:5 ID1:3 我想要这个作为 ID1:7 ID2:5 我尝试使用 LINQ。我可以删除重复但不能添加数量。

    List<PrintDetails> myList = printDetailsList
                                             .GroupBy(s => s.MasterID)
                                             .Select(grp => grp.FirstOrDefault())
                                             .OrderBy(s => s.Quantity)
                                             .ToList();

【问题讨论】:

  • 所以你想通过 id 获取聚合数量(而不是删除重复的 id)?
  • 是的......

标签: c# .net list linq


【解决方案1】:

你快到了,你只需要返回一个带有总和的新对象:

List<PrintDetails> myList = printDetailsList
    .GroupBy(s => s.MasterID)
    .Select(grp => new PrintDetails() { MasterID = grp.Key, Quantity = grp.Sum(s => s.Quantity) }) // create a new object with the Id and quantity by sum
    .OrderByDescending(s => s.Quantity) // based on the example in the question you actually want to order from highest quantity to lowest
    .ToList();

当您对列表进行分组时,您会得到一个包含 Key 并且是项目的可枚举的分组。因此,您可以将密钥用作 masterId(因为它就是这样),然后使用可枚举来对数量求和。

我还修复了您的 OrderBy,因为对于您的示例来说,这似乎是错误的方法。

Try it online

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    相关资源
    最近更新 更多