I need to modify a collection so that I can sort the sequence of items in it.
So I am doing something like:
IEnumerable<ItemType> ordered = myItems.OrderBy( (item) => item.Age);
However, I want to modify the myItems collection itself to have the ordered sequence… is it possible?
I want something like:
myItems.SomeActionHere // This should modify myItems in place.
This might be a newbie or noob question. Sorry about that.
If it’s an array you can use Array.Sort. This performs an in-place sort without duplicating references/values.
Equally, however, you can just tag
.ToArray()or.ToList()to the end of your linq statement to ‘realise’ the ordered enumerable if duplicating references is not an issue (normally it isn’t).E.g:
If you absolutely need it back as another
ReadOnlyCollectioninstance – you could do this:Note that
.ToArray()works because arrays implementIList<T>even though they’re not modifiable.Alternatively – there’s also Array.AsReadOnly – to turn it on it’s head:
Apart from being a shorter line of code I don’t see much benefit – unless reducing angle-brackets is important to you 🙂