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
Yes,
Sortis 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
OrderByoperator, 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:
You could use:
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.