【问题标题】:Linq : Group by and sum based on another listLinq:根据另一个列表分组和求和
【发布时间】:2021-08-20 14:49:29
【问题描述】:

我有以下数据列表(从 Json 列获取)

public class ProductType
{
    public string FieldName{ get; set; }
    public List<string> items { get; set; }
    
}
List contains 
 Cart item1
      item2
      item3


 wish item4
      item2
      item6

我有另一个列表,其中包含与 ProductType 相关的值

 public class ProductCost
    {
        public string item { get; set; }
        public int Amount{ get; set; }

    }
 List contains 
    item1 50
    item2  60

我需要根据 ProductTypes 的 FieldName 列找到每个项目的总和

现在我想检索如下内容

一个列表包含

cart sum(Amount of each items eg:110)
wish sum(amount of each items eg:60)

对不起,我是 LINQ 的新手。有人可以帮助我或分享资源,我可以获得实现这一目标的提示吗?使用 for 循环我实现了这一点。但是有什么方法可以在一次 linq 执行中找到

【问题讨论】:

  • 请发布示例 json
  • { "fieldName": "cart", "items": [item1,item2 ] },
  • 如果 ProductType 有一个不在 ProductCost 列表中的项目。该怎么办?忽视?抛出错误?

标签: c# .net linq group-by


【解决方案1】:

您可以使用JoinGroupBySum 使用以下查询:

List<ProductType> allProductTypes = new List<ProductType>(); // fill
List<ProductCost> allProductCosts = new List<ProductCost>(); // fill

var costsQuery = from pt in allProductTypes
                 from ptItem in pt.items
                 join pc in allProductCosts on ptItem equals pc.item
                 group (pt, ptItem, pc) by pt.FieldName into fieldGrp
                 select (FieldName: fieldGrp.Key, SumAmount: fieldGrp.Sum(x => x.pc.Amount));

List<ProductCost> totalCosts = costsQuery
    .Select(x => new ProductCost {item = x.FieldName, Amount = x.SumAmount})
    .ToList(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2017-04-20
    • 1970-01-01
    相关资源
    最近更新 更多