Sorting by two values

I had a list of objects that were created in code, and I wanted to sort by City, then by Name. Yes, a two-value search. My basic class looked like this:

public class User {

      public string Name { get; set; }

      public string City { get; set; }


Somewhere along the line of my awesome application, a List<User> gets populated with all kinds of wonderful values. Imagine Willy Wonka and the Chocolate Factory, but way more amazing:

 List<User> stuff = … // Amazing things happen here.

 After the above line, my data looks something like this:

stuff[0] = {“Scott”,”Lansing”};
stuff[1] = {“Dave”,”Lansing”};
stuff[2] = {“Tim”,”Columbus”};

The results I want are:

In order to work this beautiful thing, I only needed one line of c#:

List<User> results = stuff.OrderBy(s => s.City).ThenBy(s => s.Title).ToList();

C’est tout! Sacre bleu!

  1. #1 by zimmer62 on May 7, 2014 - 4:59 pm

    Linq and Extension methods… you’ll find so many good one liners. Like
    List results = from u in stuff where u.City == Lansing select u;

  2. #2 by zimmer62 on May 7, 2014 - 4:59 pm

    Wow.. that got chopped up.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: