Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a List of Custom Objects

Tags:

c#

I have a class called Person which contains a property LastName, which reflects a string cooresponding to the Person's last name.

I created a List as follows:

var People = List<Person>

What I would like to do is sort the people by their LastName property in alphabetical order.

After looking at some examples, I've tried

People = People.OrderBy(p => p.LastName);

But it does not work.

like image 918
Rhs Avatar asked Nov 07 '12 23:11

Rhs


2 Answers

Using LINQ, you'd need to convert the results back into a List<Person>:

People = People.OrderBy(p => p.LastName).ToList();

Since OrderBy returns an IOrderedEnumerable<T>, you need the extra call ToList() to turn this back into a list.

However, since you effectively want an in-place sort, you can also use List<T>.Sort directly:

People.Sort((p1, p2) => p1.LastName.CompareTo(p2.LastName));
like image 171
Reed Copsey Avatar answered Oct 05 '22 07:10

Reed Copsey


The easiest is using ToList():

People = People.OrderBy(p => p.LastName).ToList();

You need the ToList to create a new ordered List<Person>

Another option to sort the original list is using List.Sort:

People.Sort((p1,p2) => p1.LastName.CompareTo(p2.LastName));
like image 32
Tim Schmelter Avatar answered Oct 05 '22 09:10

Tim Schmelter