Search code examples
c#entity-frameworkconditional-operator

Using Ternary Operator in OrderBy Entity Framework


I've seen code similar to the following:

collection.OrderBy(x => x.StartDate == null ? 0 : 1).ThenBy(x => x.CreatedDate).To list();

I have Googled and searched this site and I can't find any explanation for what this does. Normally I order by a field in the collection by property name.

Can someone please explain to me what this does in plain English. I understand the ternary to mean if StartDate is null, order by 0, else order by 1. That doesn't make sense to me.

Thanks.


Solution

  • It's essentially ordering by CreatedDate, but in two groups. First the group where StartDate is null, then the group where StartDate is not null.

    This creates two "groups":

    .OrderBy(x => x.StartDate == null ? 0 : 1)
    

    So first you have all records where StartDate is null, followed by all records where it's not null. Then the secondary order within each "group" is by CreatedDate:

    .ThenBy(x => x.CreatedDate)
    

    So in plain English it might be described as:

    Show me all records with no StartDate, sorted by CreatedDate, followed by all records with a StartDate, sorted by CreatedDate.