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? */);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With