35

I have a list of cities.

 List<City> cities;

I'd like to sort the list by population. The code I'm imagining is something like:

 cities.Sort(x => x.population);

but this doesn't work. How should I be sorting this list?

Joe
  • 3,804
  • 7
  • 35
  • 55
  • 2
    http://stackoverflow.com/questions/2766686/how-do-i-use-a-lambda-expression-to-sort-integers-inside-a-object – devshorts May 18 '13 at 02:37
  • Joe, you have to have two arguments. One is the item and the other is the comparer. Check the example in the post I linked – devshorts May 18 '13 at 02:39
  • 1
    Let me see if I've got this right. The `Sort` function takes only one argument, which is a lambda/delegate that takes *two* arguments and should work like a <=> operator? – Joe May 18 '13 at 02:40

4 Answers4

62

Use OrderBy of Linq function. See http://msdn.microsoft.com/en-us/library/bb534966.aspx

cities.OrderBy(x => x.population);
David
  • 15,894
  • 22
  • 55
  • 66
19

Use this ,this will work.

List<cities> newList = cities.OrderBy(o=>o.population).ToList();
Rajasekar Gunasekaran
  • 1,799
  • 3
  • 24
  • 40
7

You can do this without LINQ. See the IComparable interface documentation here

cities.Sort((x,y) => x.Population - y.Population)

Or you can put this Comparison function within the City class,

public class City : IComparable<City> 
{
    public int Population {get;set;}

    public int CompareTo(City other)
    {
        return Population - other.Population;
    }
 ...
}

Then you can just do,

cities.Sort()

And it will return you the list sorted by population.

WaughWaugh
  • 1,012
  • 10
  • 15
2

As another option, if you aren't fortunate enough to be able to use Linq, you can use the IComparer or IComparable interface.

Here is a good KB article on the two interfaces: http://support.microsoft.com/kb/320727

Wyatt Earp
  • 1,783
  • 13
  • 23