Pergunta

I need to get a count of unique items in a list of orders.

I have a list of orders, and each order has a list of items.

public class Order
{
   public int orderID;
   public List<items> itemList;
}

public class Item
{
   public int itemID;
   public int itemQuantity;
   public String itemDescription;
}

My end goal is a list of the unique items (based on itemID or itemDescription) with a total count of each unique item.

I have the following so far, but I am unsure what to do next:

var x = from order in orders
from items in order.OrderItems
group // I know I need to group them here
select new { // I have to count in here };

I need the outcome to look like this:

  • ID: Item_01, Count: 15
  • ID: Item_02, Count: 3
  • ID: Item_03, Count: 6

Any help or direction on this would be great. Thanks.

Foi útil?

Solução

This will sum up using both the ItemID and ItemDescription values:

var x = from order in orders
            from item in order.OrderItems
            group item by new { ItemID = item.itemID, ItemDescription = item.itemDescription } into g
            select new { ItemID = g.Key.ItemID, ItemDescription = g.Key.ItemDescription, Count = g.Sum(o => o.itemQuantity) };

Outras dicas

Orders.SelectMany(x => x.itemList)
        .GroupBy(x => x.itemID)
        .Select(x => new { itemID = x.Key, Count = x.Count() })
        .ToList()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top