C# – List OrderBy Alphabetical Order


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(???? => ?????)

Best Solution

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