CodingHero
CodingHero

Reputation: 3025

Does List<T> Sort modify the collection?

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

Upvotes: 4

Views: 2686

Answers (2)

JaredPar
JaredPar

Reputation: 754803

Yes the List<T>.Sort method does indeed sort the collection in place and hence modifies the collection. If you want instead to get a new collection which is sorted that doesn't modify the original then use the OrderBy extension method.

List<int> theList = ...;
theList.Sort();  // In place mutating sort. Has a void return
List<int> sorted = theList
  .OrderBy(Comparer<int>.Default)
  .ToList();

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500865

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.

Upvotes: 10

Related Questions