【问题标题】:Check the sum of a property of list items against another property对照另一个属性检查列表项属性的总和
【发布时间】:2019-12-16 14:47:48
【问题描述】:

我有一份订单上的商品清单以及订单总额。我正在尝试找到一种方法来将所有已发货的数量相加,并将其与总订单数量进行比较,以查看是否有任何“延期交货”。

我收到了一份 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});

如何使用 LINQ 将 ShippedQty 总数与 OrderTotal 进行比较?

【问题讨论】:

  • 是否还有类似Order 的类,您是否从数据库中获取数据?您提供可运行的代码固然很好,但真正的查询在实际的应用程序代码中可能必须有很大的不同。

标签: c# list linq sum


【解决方案1】:

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

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);

假设OrderIdOrderTotal 始终链接,因此您可以按它们进行分组,并且每个OrderId 始终有一个组。

但正如我在评论中所说,如果数据来自数据库,则可能有更好的方法来获取数据,尤其是。当有一个Order 的集合导航属性包含PartInfos。

【讨论】:

    【解决方案2】:

    我的阅读是 ShippedQty 用于订单的单个项目 (Name),因此您想按 OrderId 对项目进行分组并计算发货数量。在这种情况下,您可以使用 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
        });
    

    对于示例数据,这给出了一个结果,一个具有三个 int 属性的匿名类型(来自 C# 交互式控制台):

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

    然后您可以过滤掉结果以查看订单数量小于订单总数的地方

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

    【讨论】:

    • 当我尝试这个时计数已关闭。我选择了 Gert 上面的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2021-09-30
    • 2020-07-19
    相关资源
    最近更新 更多