Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does List<T> Sort modify the collection?

Tags:

c#

.net

does List Sort modify the collection?

I think it must as I get a "System.InvalidOperationException: Collection was modified; enumeration operation may not execute." exception on another thread.

In my multi-threaded app all threads I thought were just reading the collection BUT one thread does a sort.

Thanks

like image 618
CodingHero Avatar asked Oct 20 '25 09:10

CodingHero


1 Answers

Yes, Sort is in-place, if that's what you mean, and it will certainly invalidate any iterators.

If you want to see a sorted "view" of the collection, you can use LINQ's OrderBy operator, which doesn't modify the existing collection but returns a sequence which contains the elements from the original collection, but in the given order.

So for example, instead of:

// I want to print out the list of names, sorted...
names.Sort();
foreach (string name in names)
{
    Console.WriteLine(name);
}

You could use:

foreach (string name in names.OrderBy(x => x))
{
    Console.WriteLine(name);
}

Another alternative is just to sort it once when you first populate the list, before anything starts iterating over it - that's the only modification required, and if the sort order won't change (e.g. due to modifications to the objects referred to in the list) then it would make sense to just do it once.

like image 112
Jon Skeet Avatar answered Oct 21 '25 23:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!