Archive for April, 2014

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!