Atish Kumar Dipongkor
Atish Kumar Dipongkor

Reputation: 10422

Why it give me the same output?

first run the following code

var list = new List<int> {1, 5, 0, 65, 2, 1, 0, 10};

            var ordered = list.OrderBy(i => ++i);

            foreach (var i in ordered)
            {
                Console.WriteLine(i);
            }

Output: 0 0 1 1 2 5 10 65

then,

var list = new List<int> {1, 5, 0, 65, 2, 1, 0, 10};

            var ordered = list.OrderBy(i => --i);

            foreach (var i in ordered)
            {
                Console.WriteLine(i);
            }

output: same as before

My question is why this happens??

Upvotes: 1

Views: 141

Answers (3)

JDB
JDB

Reputation: 25875

Perhaps you were expecting to sort everything by its negative value (effectively reversing the sort)? In that case, you can use OrderByDescending:

var list = new List<int> {1, 5, 0, 65, 2, 1, 0, 10};

var ordered = list.OrderBy(i => i);

foreach (var i in ordered)
{
    Console.WriteLine(i);
}

Output: 0 0 1 1 2 5 10 65

var list = new List<int> {1, 5, 0, 65, 2, 1, 0, 10};

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

foreach (var i in ordered)
{
    Console.WriteLine(i);
}

Output: 65 10 5 2 1 1 0 0

++ and -- change the value of the variable by plus or minus 1, respectively. They do not change the sign of the variable.

int x = 5;
--x;

After executing the above, the value of x would be 4.

Upvotes: 1

Servy
Servy

Reputation: 203825

The variable i in your example is not an alias to the item in the list, it is in fact a copy of the value of that item in the list. Mutating that copy will not mutate the item in the sequence itself.

Note that, by design, the LINQ operations should avoid causing side effects with the delegates that they take. They are designed for querying a sequence, and as such they shouldn't be changing the sequence itself. The LINQ "style" of programming would say that you should instead create a new sequence that was based on the list that you have, but with each item slightly changed. This is called a "projection" and is done using the Select method:

var newList = list.Select(i => i + 1)
    .OrderBy(i => i);

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503290

My question is why this happens??

Your second form is effectively the same as:

var ordered = list.OrderBy(i => i - 1);

... which isn't going to change the ordering unless you've got a value of Int32.MinValue.

The fact that you change the value of the parameter in the lambda expression is irrelevant - that parameter value is effectively thrown away afterwards. It doesn't change the value in the sequence. If you want output of -1 -1 0 0 1 4 9 64 then you should use:

var ordered = list.Select(i => i - 1).OrderBy(i => i);

Upvotes: 10

Related Questions