- Posted by Shay Friedman on April 15, 2011
Assuming you have the next code:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Whatever
{
public void Do()
{
var people = new List<Person>
{
new Person {Name = "Shay Friedman", Age = 27},
new Person {Name = "Shawn Doe", Age = 51},
new Person {Name = "Elvis Presley", Age = 76}
};
}
}
And now you want to order it first by name and then by age using LINQ. If you were to do that:
var orderedPeople = people.OrderBy(p => p.Name).OrderBy(p => p.Age);
You would get incorrect results:

That’s because the second OrderBy call just overrides the first call results. To fix that, use the ThenBy LINQ method:
var orderedPeople = people.OrderBy(p => p.Name).ThenBy(p => p.Age);
And now everything works as expected:

All the best,
Shay.