C# List<> 按照/分组/移除排序

8
哦,我从哪里开始呢... 好的,我有一个列表,我必须根据两个属性将它“切成”更小的列表。当我完成小列表的工作后,我希望它的项目从原始列表中删除 :)
例如,我有一个包含两个值CustomerID和ProductID的List<> CustomerProducts。我从对列表进行排序开始:

var orderedList = CustomerProducts.OrderBy( c => c.CustomerID).ThenBy( c => c.ProductID)ToList( );

假设排序后的列表现在看起来像这样:

CustomerID = 1, ProductID = 61
CustomerID= 1, ProductID = 61
CustomerID= 1, ProductID = 87
CustomerID= 2, ProductID = 81
CustomerID= 2, ProductID = 53

现在,我想要一个新列表,其中仅包含列表中的前两个项目(因为它们具有相同的CustomerID和ProductID),并从orderedList中删除这两个项目,然后继续执行相同的操作... while orderedList不为空。
类似于...

while(orderedList.Count > 0)
{
//create new list that has the same values...
//do some work on the new list
//remove the new list from the orderedList
//continue...
}

有没有聪明的解决方案? 聪明意味着代码短小而漂亮 :)

1
为了确保您得到解决问题的答案 - 您是否真的需要维护那个逐渐变小的有序列表(这可能至少有点昂贵),还是只需要按顺序处理匹配的客户ID /产品ID组中的项目?前者需要不断构建新列表(或从开头删除,两种操作都相对昂贵),而后者可以使用相当直接的分组操作。 - Jonathan Rupp
我同意Jonathan的评论。听起来你已经有了解决问题的想法,但是在实现过程中遇到了困难。与其告诉我们你正在尝试使用的锤子,不如告诉我们你正在建造的房子;对于管道来说,锤子可能不是正确的工具。你能否通过你正在执行的业务操作来描述问题,而不是通过你提出的可变列表解决方案的实现细节来描述问题? - Eric Lippert
1个回答

15
var groupedList = orderedList
  .GroupBy(c => new {c.CustomerId, c.ProductId})
  .OrderBy(g => g.Key.CustomerId)
  .ThenBy(g => g.Key.ProductId)
  .ToList();

foreach(var group in groupedList)
{
  List<CustomerProduct> cps = group.ToList();
  //do some work with this customer products

  //no need to do inefficient list removal - just move on to next group.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接