The life of a code monkey

Text

LINQ OrderByDescending gotcha.

As I discovered today 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.

Posted on Wednesday, June 8 2011. Tagged with: LINQOrderByOrderByDescendingSortStable SortSortingC
243
Notes
  1. dictionaryde2 liked this
  2. differences56f liked this
  3. coalitiong9p liked this
  4. arolking54g liked this
  5. dotnetgeek posted this
Got a question or comment? Ask me.
Previous Next