Search
Tuesday, November 20, 2018 ..:: Home ::.. Register  Login
   Calendar  
     
  
   Search  
     
  
   Blogroll  
     
  
   Disclosure  
All blog entries are the opinions of the author and do not necessarily reflect the opinions of their employer. All the code presented is for explanation and demonstration purposes only. Any damages incurred to your site and/or data are not the responsibility of the author. Every effort is taken to ensure the code properly compiles, however sometimes there are some hiccups and you might be required to do your own debugging.
     
  
   TechTidBits (Blog)  

How do you sort nulls last in Linq?

Sep 25

Written by:
Wednesday, September 25, 2013 8:05 PM  RssIcon

image

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!)

image

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).

image

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.

image

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!

 

Resources

stackoverflow: SQL how to make null values come last when sorting ascending

Tags:
Categories:
Location: Blogs Parent Separator TechTidBits

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Add Comment   Cancel 
     
  
Copyright 1999-2012 by PCHenry.com   Terms Of Use  Privacy Statement