List<T> OrderBy Alphabetical Order

SaaS Developer picture SaaS Developer · Oct 9, 2008 · Viewed 690.5k times · Source

I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<T>. For the sake of this example, let's say I have a List of a Person type with a property of lastname. How would I sort this List using a lambda expression?

List<Person> people = PopulateList();
people.OrderBy(???? => ?????)

Answer

Marc Gravell picture Marc Gravell · Oct 9, 2008

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional