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.