简体   繁体   中英

Linq Count Unique Values in List

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.

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) };
Orders.SelectMany(x => x.itemList)
        .GroupBy(x => x.itemID)
        .Select(x => new { itemID = x.Key, Count = x.Count() })
        .ToList()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM