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?
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?
Use OrderBy of Linq function. See http://msdn.microsoft.com/en-us/library/bb534966.aspx
cities.OrderBy(x => x.population);
Use this ,this will work.
List<cities> newList = cities.OrderBy(o=>o.population).ToList();
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.
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