Michael
Michael

Reputation: 13636

Some misunderstanding about sort extensions

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.

Upvotes: 0

Views: 77

Answers (2)

Hans Kesting
Hans Kesting

Reputation: 39329

The list.Reverse() method reverses the list in-place, so your original list is changed.

The .OrderByDescending() extension method produces a new list (or rather an IEnumerable<T>) and leaves your original list intact.

EDIT
To get two lists, for both sort orders:

List<int> upList = list.OrderBy(n => n).ToList();
List<int> downList = list.OrderByDescending(n => n).ToList();

Upvotes: 6

Tim Schmelter
Tim Schmelter

Reputation: 460228

Edit: So the problem seems to be that you think that the Enumerable extensions would change the original collection. No they do not. Actually they return something new you need to asign to a variable:

IEnumerable<int> ordered = list.OrderByDescending(n => n);
foreach(int i in ordered)
    Console.WriteLine(i);

OrderByDescending orders 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:

var ordered = list.OrderByDescending(n=> n);

This returns an "arbitrary" order:

list.Reverse()

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 OrderBy or OrderByDescending if you want to order a sequence and Reverse if you want to invert the sequence what is not necessarily an order (it is at least confusing).

Upvotes: 2

Related Questions