代码之家  ›  专栏  ›  技术社区  ›  IanCaz

检查列表项的属性与其他属性的总和

  •  0
  • IanCaz  · 技术社区  · 5 年前

    我有一个订单上的项目列表,以及订单总数。我正试图找到一种方法,将所有已发货的数量加起来,并将其与总订单数量进行比较,看看是否有“缺货”。

    我得到了一份PartInfo的列表,其中包括订单中此产品的所有发货。

    public class PartInfo
    {
            public int OrderId { get; set; }
            public string Name { get; set; }
            public string TrackingId { get; set; }
            public int ShippedQty { get; set; }
            public int OrderTotal { get; set; }
    }
    

    如果我使用以下数据:

    List<PartInfo> PartList = new List<PartInfo>();
    PartList.Add(new PartInfo() { OrderId = "1031",
                                  Name = "Watch", 
                                  TrackingId = "1Z204E380338943508", 
                                  ShippedQty = 1, 
                                  OrderTotal = 4});
    
    PartList.Add(new PartInfo() { OrderId = "1031",  
                                  Name = "Watch", 
                                  TrackingId = "1Z51062E6893884735", 
                                  ShippedQty = 2, 
                                  OrderTotal = 4});
    

    0 回复  |  直到 5 年前
        1
  •  1
  •   Gert Arnold    5 年前

    直接的答案可能是这样的:

    var backOrdered = partList.GroupBy(p => new { p.OrderId, p.OrderTotal })
    .Select(g => new
    {
        g.Key.OrderId,
        g.Key.OrderTotal,
        TotalShipped = g.Sum(pi => pi.ShippedQty)
    })
    .Where(x => x.TotalShipped  < x.OrderTotal);
    

    假设 OrderId OrderTotal 总是链接的,因此您可以按它们分组,并且每个组都有一个组 .

    但正如我在评论中所说,如果数据来自数据库,可能有更好的方法来获取数据,特别是当 Order 集合导航属性包含 PartInfo s。

        2
  •  0
  •   BurnsBA svenningsson    5 年前

    ShippedQty Name )对于订单,因此要按 OrderId 并计算发货数量。在这种情况下,可以使用group by LINQ:

    var groupResults = PartList.GroupBy(
        // Group by OrderId
        x => x.OrderId,
        // Select collection of PartInfo based on the OrderId
        x => x,
        // For each group based on the OrderId, create a new anonymous type
        // and sum the total number of items shipped.
        (x,y) => new {
            OrderId = x,
            ShippedTotal = y.Sum(z => z.ShippedQty),
            OrderTotal = y.First().OrderTotal
        });
    

    f__AnonymousType0#3<int, int, int>> { { OrderId = 1031, ShippedTotal = 3, OrderTotal = 4 } }
    

    然后,您可以筛选出结果,以查看订单数量小于订单总数的位置

    groupResults.Where(x => x.ShippedTotal < x.OrderTotal) ...