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,
Shay.




Comments

April 15. 2011 09:27 PM

Dan Martin

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.

Dan Martin

June 12. 2011 08:04 AM

michael

Thanks Shay!

I been looking for something similar, this can help!

michael

September 23. 2011 05:03 PM

pingback

Pingback from freerob.com

HTML | Free Software | Free Templates | Freerob.com

freerob.com

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Subscribe Subscribe

That's Me!

Hi! I'm Shay Friedman
I'm Shay Friedman - a Visual C#/IronRuby MVP, a consultant and instructor of .NET technologies, author, speaker and new technologies freak
More about me

Contact Me

> Contact page
> Twitter: @ironshay
> LinkedIn profile

Search

Hosted By

I'm hosting this site on Arvixe and I'm very happy with it.
If you're looking for ASP.NET hosting, I highly recommend it
(and if you order from this link I also get some beer money!)
Web Hosting