Jonathan
Jonathan

Reputation: 15442

Placing items at top of collection using LINQ

Using LINQ, I'm looking to place items which match a certain criteria at the top of my collection. I've tried

myCollection.OrderBy(m => m.Foo == "Bar" ? 0 : 1);

but I'm having no luck. Does anyone have any ideas why this isn't working?

Thank you in advance.

Upvotes: 1

Views: 82

Answers (3)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59963

If your collection is a List<T> check out the List<T>.Sort method. Alternatively, if you're dealing with an array, use the Array.Sort method. Those methods will sort the collection in place.

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174339

All of the LINQ "operators" like Select, OrderBy etc. do not change the collection they were called on but return a new one!

Upvotes: 1

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

OrderBy() and the other LINQ methods do not modify the collection they're called on; instead, they return a new collection.

Upvotes: 6

Related Questions