Tuesday, August 9, 2016

Linq OrderBy vs ThenBy - composite ordering calling OrderBy multiple times over is not what you want to do

Do not apply multiple order by linq operators one over the output of the other - the results will not be what you want.



var sequence = new[]
{
    new {a = 10, b = 20, c = 301, d = 1},
    new {a = 1000, b = 50, c = 30, d = 0},
    new {a = 50, b = 10, c = 1130, d = 1},
    new {a = 5, b = 0, c = 130, d = 0},
};

var o1 = sequence.OrderBy(s => s.a);
var o2 = sequence.OrderBy(s => s.b);
var o3 = sequence.OrderBy(s => s.c);

var fluentSyntaxSort = sequence.OrderBy(s => s.a).OrderBy(s => s.b).OrderBy(s => s.c);

var thenBy = sequence.OrderBy(s => s.a).ThenBy(s => s.b).ThenBy(s => s.c);

Console.WriteLine("3 order bys EACH ON THE ORIGINAL sequence");
foreach (var o in o1)
    Console.WriteLine(o);
foreach (var o in o2)
    Console.WriteLine(o);
foreach (var o in o3)
    Console.WriteLine(o);

Console.WriteLine("\nFluent syntax:");
foreach (var o in fluentSyntaxSort)
    Console.WriteLine(o);

Console.WriteLine("\nThenBy:");
foreach (var o in thenBy)
    Console.WriteLine(o);

Output:


1 comment:

  1. The three fields need to be reversed between the two versions. orderby abc = orderby.thenby.thenby cba

    ReplyDelete