Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> 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(???? => ?????) 
like image 790
SaaS Developer Avatar asked Oct 09 '08 16:10

SaaS Developer


2 Answers

Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:

var peopleInOrder = people.OrderBy(person => person.LastName); 

To sort in place, you'd need an IComparer<Person> or a Comparison<Person>. For that, you may wish to consider ProjectionComparer in MiscUtil.

(I know I keep bringing MiscUtil up - it just keeps being relevant...)

like image 33
Jon Skeet Avatar answered Nov 08 '22 12:11

Jon Skeet


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 
like image 98
Marc Gravell Avatar answered Nov 08 '22 12:11

Marc Gravell