How do you sort nulls last in Linq?
Wednesday, September 25, 2013 8:05 PM
Have you tried sorting in Linq? Easy eh? Ok, How do you sort nulls last? Gotcha didn’t I? Read on, I figured it out!
Every once in a while you need to sort your collections in a weird way. One of those “weird” ways is sorting nulls last. In SQL, it’s easy enough, just put the order by NULLS last. But how do you do that in Linq? I have a GREAT trick, and it is a cool C# trick!!!!!!
First off, let’s set this up (sorry for the pics of code, I don’t have my public TFS projects completely working yet).
I created a HockeyTeam class, simple enough. Special notes, two properties and one of them is a nullable int (spoiler alert, THAT’S the one that’s going to have nulls in it), override for ToString to show nice output and a way to create sample/dummy/test data (notice how there are some teams without Championshiops…….like the Sens? DOH!)
Ok, that’s the setup. Next is the main star of the show (it’s just a console app, easy enough to illustrate my point).
The KEY here is the OrderByDescending(x => x.Championships.HasValue) as the FIRST sort criteria. Once you think about it, I’m sure you WON’T forget this trick in the future. By doing the descending order you’re FORCING all the nulls (doesn’t have a value) to the bottom. That’s it, THAT’S the trick.
Ok, so you notice I have two more sorts with the ThenBy. Yup, when you run this, I wanted to see the team with the highest championship count at the top (yes, I wanted to see my Habs at the top LOL). Then, just for good measure and to show I can still add another sort order, the last sort is by team name.
So the output looks like this.
There, so now you know the trick to get nulls to sort last (OrderByDescending and using the .HasValue property). Now it’s time to grab a coffee and get coding!
stackoverflow: SQL how to make null values come last when sorting ascending