Using OrderBy() in linq?
c#, linq
Solution
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:
myItems = myItems.OrderBy(i => i.Age).ToArray();
If you absolutely need it back as another `ReadOnlyCollection` instance - you could do this:
myItems = new ReadOnlyCollection<ItemType>(myItems.OrderBy(i => i.Age).ToArray());
Note that `.ToArray()` works because arrays implement `IList<T>` even though they're not modifiable.
Alternatively - there's also Array.AsReadOnly - to turn it on it's head:
myItems = Array.AsReadOnly(myItems.OrderBy(i => i.Age).ToArray());
Apart from being a shorter line of code I don't see much benefit - unless reducing angle-brackets is important to you :)
Problem
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.