tags:

views:

88

answers:

5

There are a few posts on the site about how to order by using lambda expressions however I cannot seem to get mine to work. I am trying to reorder a list that is already populated. Am i wrong in thinking that i can rearrange the order of this list using lambada expressions?

QuarterMileTimes.OrderByDescending(c => c.PquartermileTime); 

I was wondering if it's down to PquartermileTime being a string? I also tried this expression on a date

QuarterMileTimes.orderBy(c => c.RaceDay);

Still no luck where am I going wrong?

+1  A: 

The result of OrderByDescending (and all of the other Enumerable extension methods) is an IEnumerable<T> that projects the source data in the order you're describing. It does not alter the original data in any way.

If you prefer, you can use the ToList() extension method to create a new List<T> from that result and assign it back to the original variable.

QuarterMileTimes = QuarterMileTimes.OrderByDescending(/*...*/).ToList();

(This is assuming, of course, that QuarterMileTimes is a List<T>)

The gist of the answer is no, OrderByDescending does not alter the data source in any way.

Adam Robinson
+4  A: 

When you call OrderByDescending, the method returns a new IEnumerable<T> - it does not reorder the collection in place.

Try doing:

QuarterMileTimes = QuarterMileTimes.OrderByDescending(c => c.PquartermileTime).ToList();

(This is if your collection is a List<T>...)

Reed Copsey
Brilliant, this has solved my problem and very quickly.
Truezplaya
Glad to hear it.
Reed Copsey
+1  A: 

You are assigning it to a new variable aren't you?

var sortedTimes = QuarterMileTimes.OrderByDescending(c => c.PquartermileTime);

It isn't like e.g. the List.Sort method, that sorts the existing list.
The result of the method has to be assigned to a variable.

Zyphrax
+1  A: 

OrderByDescending returns an IOrderedEnumerable<T> i.e. a new sequence with the items in the specified order. You'll have to re-assign QuarterMileTimes to get the behaviour you expect:

QuarterMileTimes = QuarterMileTimes.OrderByDescending(c => c.PquarterMileTime).ToList();

Alternatively you can just use the returned sequence separately, which is the usual approach.

Lee
A: 

QuarterMileTimes.OrderByDescending(c => c.PquartermileTime) returns a new enumerable, ordered by PquartermileTime. It does not reorder QuarterMileTimes in place.

Winston Smith