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;
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).
source share