v4ofhg
Last Updated: February 25, 2016
·
2.249K
· keboo

LINQ OrderByDescending gotcha

The LINQ OrderBy and OrderByDescending do not always return collections that are in inversely ordered.

Consider the following code:

var array = new[]
                {
                    new {key = 3, value = "e"},
                    new {key = 1, value = "a"},
                    new {key = 2, value = "c"},
                    new {key = 2, value = "d"},
                    new {key = 2, value = "b"},
                };

Action<string[]> printArray =
    stringArray => Console.WriteLine(string.Join(", ", stringArray));

Console.WriteLine("Initial Array");
printArray(array.Select(x => x.value).ToArray());
Console.WriteLine();

Console.WriteLine("LINQ OrderBy");
var assending = array.OrderBy(x => x.key).Select(x => x.value).ToArray();
printArray(assending);
Console.WriteLine();

Console.WriteLine("LINQ OrderByDescending");
var descending = array.OrderByDescending(x => x.key).Select(x => x.value).ToArray();
printArray(descending);
Console.WriteLine();
Console.ReadLine();

Output:

Initial Array

e, a, c, d, b

LINQ OrderBy

a, c, d, b, e

LINQ OrderByDescending

e, c, d, b, a

I expected the OrderByDescending to return “e, b, d, c, a” (ie. the reverse of the call to OrderBy), but this is obviously not the case. Looking at the documentation ”This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key.” When using the OrderByDescending method if two items have equal values they will be returned in the order in which they appear in the original enumerable, not in reverse order as I had originally expected.

Source: http://dotnetgeek.tumblr.com/post/6340107541/linq-orderbydescending-gotcha

Say Thanks
Respond