Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading