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,

Comments (2) -

Thanks, this is very helpful. I ran into this issue a couple of months ago and it took a while to find out that I should use ThenBy.


Thanks Shay!

I been looking for something similar, this can help!


Pingbacks and trackbacks (1)+

Add comment