score:1

Accepted answer

first of all, a list inside a foreach is immutable, you can't add or delete content, nor rewrite an element. there are a few ways you could handle this situation:

groupby

this is the method i would use. you can group your list by the property you want, and iterate through the igrouping formed this way

var groups = list.groupby(x => x.yourproperty);
foreach(var group in groups)
{
//your code
}

distinct properties list

you could also save properties in another list, and cycle through that list instead of the original one

var propslist = list.select(x=>x.yourproperty).distinct();
foreach(var prop in propslist)
{
    var tmplist = list.where(x=>x.yourproperty == prop);
    //your code
}

while loop

this will actually do what you originally wanted, but performances may not be optimal

while(list.any())
{
    var prop = list.first().yourproperty;
    var tmplist = list.where(x=>x.yourproperty == prop);
    //your code
    list.removeall(x=>x.yourproperty == prop);
}

score:3

first off, using foreach in your example isn't a great idea for these reasons.

you're right to think there are performance downsides to iterating through the full list for each remaining someid, but even making the list smaller every time would still require another full iteration of that subset (if it even worked).

as was pointed out in the comments, groupby on someid organizes the elements into groupings for you, and allows you to efficiently step through each subset for a given someid, like so:

_mylist.groupby(x => x.someid)
       .select(g => dosomethingwithgroupedelements(g));

jon skeet has an excellent set of articles about how the linq extensions could be implemented. i highly recommend checking it out for a better understanding of why this would be more efficient.


Related Query