Ironing code, geek t-shirts and even presentations!


LINQ Tip: Chain Ordering

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:

LINQ Tip: Results when using OrderBy after an OrderBy call.

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:

LINQ Tip: Using ThenBy after an OrderBy call.

All the best,