Linq查询加入两个对象并计算总和

时间:2017-03-02 12:52:07

标签: c# linq sum

我需要在Sku上加入两个对象列表,然后对SumQty * Price)进行计算。我不确定该怎么做?以下是我到目前为止的情况:

List<Order> orders = new List <Order> 
{ 
    new Order() { Sku = "ABC", Qty = 1 },
    new Order() { Sku = "XYZ", Qty = 2}
};

List<Cost> costs = new List <Cost> 
{ 
    new Cost() { Sku = "ABC", Price = 4.50m },
    new Cost() { Sku = "XYZ", Price = 2.25m }
};


var profit = from order in orders
             join cost in costs
             on order.Sku equals cost.Sku
             select Sum(order.Qty * cost.Price)

1 个答案:

答案 0 :(得分:5)

按如下方式更改您的最后一部分:

var profit = (from order in orders
             join cost in costs
             on order.Sku equals cost.Sku
             select (order.Qty * cost.Price)).Sum();

从这里采取:Stackoverflow question that answered how to sum