tags:

views:

2353

answers:

1

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:

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

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.

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

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

+5  A: 
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.
}
David B
this works perfectly! thanx
JaneV