Linq ThenBy Possibly Null

I am trying to sort the view model binding with several properties. The problem is that the second property can be NULL, and I get an exception with a null reference.

return this.People .OrderBy(x => x.Car.Name) .ThenBy(x => x.Pet.Name); 

What if Pet is null? How am I still doing ThenBy sort by name Pet.Name?

+4
source share
4 answers

This should return null Pets in front of unnecessary pets.

 return this.People .OrderBy(x => x.Car.Name) .ThenBy(x => x.Pet != null ? x.Pet.Name : ""); 
+9
source

If you want people who don't have pets to be sorted higher than those who have pets, you can use this:

 return this.People .OrderBy(x => x.Car.Name) .ThenBy(x => x.Pet == null ? string.Empty : x.Pet.Name); 

If you intend to perform many sorting operations involving pets, you can create your own PetComparer class, which inherits from Comparer<Pet> , for example:

 public class Pet { public string Name { get; set; } // other properties } public class PetComparer : Comparer<Pet> // { public override int Compare(Pet x, Pet y) { if (x == null) return -1; // y is considered greater than x if (y == null) return 1; // x is considered greater than y return x.Name.CompareTo(y.Name); } } 

Now your request will look like this:

 return this.People .OrderBy(x => x.Car.Name) .ThenBy(x => x.Pet, new PetComparer()); 

Note: this will do the opposite of the query at the top of this answer - it will sort people without pets to the bottom (within the name of the car).

+3
source

You can use the null object template for pets and cars to avoid any additional null checks in such cases and to minimize the risk of a possible NullReferenceException ,

+2
source

Using conditional operators null ( ?. ) And combining null ( ?? ) together, you can do this -

 return this.People .OrderBy(x => x.Car.Name) .ThenBy(x => x.Pet?.Name ?? string.Empty); 
0
source

All Articles