user1202434
user1202434

Reputation: 2273

Using OrderBy() in linq?

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.

Upvotes: 3

Views: 4167

Answers (4)

Andras Zoltan
Andras Zoltan

Reputation: 42363

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 :)

Upvotes: 11

tech-man
tech-man

Reputation: 3256

Use SortedList or convert to a SortedList.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292685

OrderBy (like most other Linq operators) is lazy; it doesn't materialize its results, it just re-reads the source collection every time. So if you change the content of myItems, every time you will enumerate ordered you will see the latest changes in myItems.

Upvotes: 0

Daren Thomas
Daren Thomas

Reputation: 70344

You won't be able to use Linq to order your collection i place. Unless you go specifically go and implement OrderBy for your sequence type.

Upvotes: 2

Related Questions