Order on multiple fields with LINQ

This is one of the things I tend to forget when I need to order a list on multiple fields using LINQ. I often start with chaining OrderBy() methods, only to realize that that doesn’t work. When you do that, only the last OrderBy() is taken into account.

What you need to do is start with an OrderBy() (or OrderByDescending()) and then chain ThenBy() (or ThenByDescending()) methods. It actually makes some sense and it is certainly easier to read. I bet I’m not the only one forgetting this.

List<Fruit> fruits = new List<Fruit>
{
	new Fruit { Name="Apple", Color="Red" },
	new Fruit { Name="Apple", Color="Yellow" },
	new Fruit { Name="Plum", Color="Purple" },
	new Fruit { Name="Strawberry", Color="Red" },
	new Fruit { Name="Banana", Color="Yellow" },
	new Fruit { Name="Apple", Color="Green" },
	new Fruit { Name="Orange", Color="Orange"},
	new Fruit { Name="Tangerine", Color="Orange" },
	new Fruit { Name="Lemon", Color="Yellow" }
};

// This one is only ordered by Name
var sorted = fruits.OrderBy(f => f.Name);

// This one is only ordered by Color, not by Name
var sorted2 = fruits.OrderBy(f => f.Name).OrderBy(f => f.Color);

// This one is ordered by Name and then by Color
var sorted3 = fruits.OrderBy(f => f.Name).ThenBy(f => f.Color);
This entry was posted in Development and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please leave these two fields as-is: