PixelPaul
PixelPaul

Reputation: 2767

Linq query to join two objects and calculate sum

I have two lists of objects that I need to join on Sku and then caluclate the Sum (Qty * Price). I'm not exactly sure how to do this? Here is what I have so far:

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)

Upvotes: 1

Views: 1626

Answers (1)

Ori Nachum
Ori Nachum

Reputation: 598

Change your last part as follows:

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

Taken from here: Stackoverflow question that answered how to sum

Upvotes: 5

Related Questions