HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

List<T> OrderBy Alphabetical Order

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
orderbylistalphabeticalorder

Problem

I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List. 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 people = PopulateList();
people.OrderBy(???? => ?????)

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

Code Snippets

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));
var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

Context

Stack Overflow Q#188141, score: 748

Revisions (0)

No revisions yet.