【问题标题】:Linq Count Unique Values in ListLinq 计算列表中的唯一值
【发布时间】:2013-08-12 18:51:45
【问题描述】:

我需要计算订单列表中唯一商品的数量。

我有一个订单列表,每个订单都有一个商品列表。

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

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

我的最终目标是一个唯一项目列表(基于 itemID 或 itemDescription)以及每个唯一项目的总数。

到目前为止,我有以下内容,但我不确定下一步该做什么:

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 };

我需要这样的结果:

  • ID:Item_01,数量:15
  • ID:Item_02,数量:3
  • ID:Item_03,数量:6

对此的任何帮助或指导都会很棒。谢谢。

【问题讨论】:

  • @V.B.感谢您的快速回复。我现在就看看这个。会让你知道结果如何。
  • @V.B.抱歉,这个例子对我不起作用。下面的解决方案效果很好。
  • 这只是一个方向。尼克的答案朝着相同的方向工作,但可以很好地满足您的需求。

标签: c# linq list grouping counting


【解决方案1】:

这将使用 ItemID 和 ItemDescription 值进行总结:

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) };

【讨论】:

    【解决方案2】:
    Orders.SelectMany(x => x.itemList)
            .GroupBy(x => x.itemID)
            .Select(x => new { itemID = x.Key, Count = x.Count() })
            .ToList()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 2014-04-07
      • 2019-05-15
      相关资源
      最近更新 更多