Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of objects by a specific member?

Say I have a list of Person objects:

class person
{
  int id;
  string FirstName;
  string LastName;
}

How would I sort this list by the LastName member?

List<Person> myPeople = GetMyPeople();
myPeople.Sort(/* what goes here? */);
like image 780
Abe Miessler Avatar asked Jun 24 '10 20:06

Abe Miessler


1 Answers

List<T>.Sort will sort the list in-place. If that's what you want, sweet: use the overload that takes a Comparison<T> delegate:

List<Person> myPeople = GetMyPeople();
myPeople.Sort((x, y) => x.LastName.CompareTo(y.LastName));

If you don't want to modify the actual list but want to enumerate over its contents in a sorted order, then, as others have suggested, use the LINQ extension method OrderBy (.NET 3.5 and up) instead. This method can take a simple Func<T, TKey> selector and order by the keys which this selector... you know, selects.

List<Person> myPeople = GetMyPeople();
var orderedByLastName = myPeople.OrderBy(p => p.LastName);
like image 131
Dan Tao Avatar answered Oct 01 '22 20:10

Dan Tao