Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of objects by the value of a property [duplicate]

Tags:

c#

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?

like image 217
Joe Avatar asked May 18 '13 02:05

Joe


People also ask

How do you sort an array of objects based on a property?

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.

How do you sort a list of objects based on an attribute of the objects in C#?

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.

How do you sort an object by property in powershell?

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.

Can you sort a list of objects in Python?

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.


1 Answers

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

cities.OrderBy(x => x.population); 
like image 103
David Avatar answered Sep 26 '22 09:09

David