Bioaim
Bioaim

Reputation: 1016

LINQ count field of selected objects

I have a PurchaseOrder and OrderItem class. Inside of a PurchaseOrder I have an array of OrderItem.

An OrderItem has a ItemName and a Quantity.

Now i want to get the count of the Quantity of all OrderedItems over all PurchaseOrders with a given ItemName.

var query = PurchaseOrders.Select(order => from item in order.OrderedItems where itemName == item.ItemName)

This is how far i came, but that only returns orders which do have an itemName in their order, which is far from my goal.

How can i achieve that in LINQ?

Upvotes: 0

Views: 1017

Answers (1)

Fabio
Fabio

Reputation: 32445

To get total quantity for only one name use SelectMany to get collection of all items from collection of orders.

var count = PurchaseOrders
    .SelectMany(order => order.OrderedItems)
    .Where(item => item.ItemName == "name")
    .Sum(item => item.Quantity);

With combination of SelectMany and GroupBy you can build a dictionary where Key is a name of item and Value is a total quantity of items with corresponding name.

var quantities = PurchaseOrders
    .SelectMany(order => order.OrderedItems)
    .GroupBy(item => item.ItemName)
    .ToDictionary(group => group.Key, group => group.Sum(item => item.Quantity));

// Then you can get total quantity for any name
var quantity = quantities.GetValueOrDefault("firstItem");

Upvotes: 2

Related Questions