views:

37735

answers:

3

I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<>. For the sake of this example lets 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(???? => ?????)
A: 

people.OrderBy(person => person.lastname).ToList();

Danimal
That won't capture the result; OrderBy returns a new IEnumerable<T> list.
Marc Gravell
Ah, good point, Mark -- corrected
Danimal
Well, that still doesn't capture the result - you'd need a "List<Person> people = " on the left hand side...
Marc Gravell
+6  A: 

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...)

Jon Skeet
+57  A: 

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
Marc Gravell
I believe that first one wants to be people.Sort((x, y) => string.Compare(x.LastName, y.LastName) < 0);
James Curran
@James: I wouldn't think so. Comparison<T> returns int, not bool.
Jon Skeet
What Jon said...
Marc Gravell
I wonder if you want to OrderBy Firstname and Lastname... what should you write?
balexandre
var newList = people.OrderBy(x=>x.FirstName).ThenBy(x=>x.LastName).ToList();
Marc Gravell