I have the following code example:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Add(6);
list.Add(7);
list.OrderByDescending(n=>n).Reverse();
But when I use this:
list.OrderByDescending(n=>n).Reverse();
I don’t get wanted result.
If instead of the above statement, I use this one:
list.Reverse();
I get the wanted result.
Any idea why I don’t get wanted result using the first statement ?
I believe I am missing something in understanding the extensions.
Thank you in advance.
Edit: So the problem seems to be that you think that the
Enumerableextensions would change the original collection. No they do not. Actually they return something new you need to asign to a variable:OrderByDescendingorders descending(highest first) which is what you obviously want. So i don’t understand why you reverse it afterwards.So this should give you the expected result:
This returns an “arbitrary” order:
since it just reverses the order you have added the
ints. If you have added them in an ordered way you don’t need to order at all.In general: use
OrderByorOrderByDescendingif you want to order a sequence andReverseif you want to invert the sequence what is not necessarily an order (it is at least confusing).