10

I have a class called Person which contains a property LastName, which reflects a string cooresponding to the Person's last name.

I created a List as follows:

var People = List<Person>

What I would like to do is sort the people by their LastName property in alphabetical order.

After looking at some examples, I've tried

People = People.OrderBy(p => p.LastName);

But it does not work.

2
  • 1
    by the way, ALWAYS specify what you mean by does not work. Is it a compilation error? or a runtime error? or unexpected results?, etc. Commented Nov 7, 2012 at 23:08
  • Possible duplicate: Custom Sorting of List<T> Commented Dec 10, 2012 at 21:51

3 Answers 3

18

Using LINQ, you'd need to convert the results back into a List<Person>:

People = People.OrderBy(p => p.LastName).ToList();

Since OrderBy returns an IOrderedEnumerable<T>, you need the extra call ToList() to turn this back into a list.

However, since you effectively want an in-place sort, you can also use List<T>.Sort directly:

People.Sort((p1, p2) => p1.LastName.CompareTo(p2.LastName));
Sign up to request clarification or add additional context in comments.

Comments

2

The easiest is using ToList():

People = People.OrderBy(p => p.LastName).ToList();

You need the ToList to create a new ordered List<Person>

Another option to sort the original list is using List.Sort:

People.Sort((p1,p2) => p1.LastName.CompareTo(p2.LastName));

Comments

0

You need to convert the result of orderby to .Tolist() like below

var people = People.OrderBy(p => p.LastName).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.