C# 列表<> 排序依据/分组依据/删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1399261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:05:40  来源:igfitidea点击:

C# List<> Order by/Group by/Remove

c#list

提问by

Phew where do I begin... OK, I have a list that I have to ,,cut up'' into smaller list depending on two properties. When I have finished working with the small list I want it's items removed from the original list :)

呼我从哪里开始......好吧,我有一个列表,我必须根据两个属性将其切割成更小的列表。当我完成小列表的工作后,我希望将其从原始列表中删除:)

f.ex. I have a List<> CustomerProducts, that contains two values CustomerID and ProductID. I begin by ordering the list:

例如 我有一个 List<> CustomerProducts,它包含两个值 CustomerID 和 ProductID。我首先对列表进行排序:

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

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

Assume the ordereded list now looks like this:

假设有序列表现在看起来像这样:

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

客户ID = 1,产品ID = 61
客户ID= 1,产品ID = 61客户ID=
1,产品ID = 87
客户ID= 2,产品ID = 81
客户ID= 2,产品ID = 53

Now I want a new list that contains only the first two items in the list (because they have the same CustomerID and ProductID), and remove these two items from the orderedList, and then continue doing the same to the rest ... while the orderedList is not empty.

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

somehting like...

有点像……

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

while(orderedList.Count > 0)
{
//创建具有相同值
的新列表... //对新列表做一些工作
//从orderedList中删除新列表
//继续...
}

Any ideas of a smart solution for this?? smart meaning short code and pretty ofcourse :)

对此有任何智能解决方案的想法吗?聪明的意思是短代码和漂亮的当然:)

采纳答案by Amy B

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