Difference between using consecutive OrderBy()'s instead of ThenBy()

82 Views Asked by At

I am confused as to why these two pieces of code creates two different results. I would expect the second one, using ThenBy() to generate the correct result, but it does not. The first one (something I tried during debugging) creates the right result (But it seems to be by coincidence).

I want it to order like this:

Order everything by the property "FileDate" in descending order. Then order the items that are of the event type (using .IsEvent() extension) by it's "FileDate" by ascending order. Then, order it by name, so items that has the same date is ordered alphabetically.

var firstSort = nodeList.OrderByDescending(x => x.FileDate);
var secondSort = firstSort.OrderBy(x => x.IsEvent() ? x.FileDate : DateTime.MinValue);
var thirdSort = secondSort.OrderBy(x => x.Name);

The result in thirdSort is the correct result. The result i expect. But it's a bad piece of code I think.

var sortedSet = nodeList.OrderByDescending(x => x.FileDate)
                .ThenBy(x => x.IsEvent() ? x.FileDate : DateTime.MinValue)
                .ThenBy(x => x.Name)
                .Skip(amountToSkip).Take(pageSize);

This does not create the result i expect. But I like that piece of code more.

Can someone ILI5 why these create different results? And also how I get the right result, not using consecutive OrderBy() calls.

Here is some example data, the result, and the expected result:

Format: Name (Type) (FileDate)

Input (nodeList):

  • An exciting event (Event type) (24-11-2023)
  • Another event (Event type) (16-11-2023)

Result:

  • An exciting event (Event type) (24-11-2023)
  • Another event (Event type) (16-11-2023)

Expected result:

  • Another event (Event type) (16-11-2023)
  • An exciting event (Event type) (24-11-2023)
1

There are 1 best solutions below

0
JonasH On BEST ANSWER

ThenBy is used when the primary order value is the same. You first order by date, and if the date is the same, then you order these values by name.

OrderBy on the other hand just do a completely new sort, even it it is stable.

In your example there are no cases where either the date or the name is the same.So your example that uses OrderBy will in effect only order by name. And your ThenBy example will only order by date, descending.

So the result is completely as expected, even if I'm not sure what result you actually want.

Example:

Say I have objects composed of pairs of letters and numbers, say a2, b2, a1, c1. And we use OrderBy first for letter and then for number we would get a1, c1, a2, b2. The reason is that we produce the intermediate sorting of a2, a1, b2, c1, and then do a stable sort of that.

Using OrderBy letter, and ThenBy number will produce a1, a2, b2, c1, since it will only use the number for ordering if the letter is the same.