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?
Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.
C# has a built-in Sort() method that performs in-place sorting to sort a list of objects. The sorting can be done using a Comparison<T> delegate or an IComparer<T> implementation.
If you want to sort by multiple properties, separate the properties by commas. The Get-ChildItem cmdlet gets the files from the directory specified by the Path parameter. The objects are sent down the pipeline to the Sort-Object cmdlet.
A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.
Use OrderBy of Linq function. See http://msdn.microsoft.com/en-us/library/bb534966.aspx
cities.OrderBy(x => x.population);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With