2

How to sort a list in C# with secondary sorting. For example if I have a class called Student with two fields FirstName and LastName. Until now I've sorted the list as follows:

MyStudents.Sort((s1, s2) => s1.LastName.CompareTo(s2.LastName));

I wanted to know how can I sort the list first by last name and then by first name. Thanks.

3 Answers 3

8

Sort doesn't have that capability.

Linq can do this simply:

MyStudents.OrderBy(s => s.LastName).ThenBy(s => s.FirstName)

Ensure you are using at least .NET 3.5 and have the System.Linq namespace referenced.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use LINQ:

MyStudents.OrderBy(e => e.LastName).ThenBy(e => e.FirstName);

1 Comment

you have a typo - ThenBy not ThanBy
2

You can use OrderBy and ThenBy

var sortedList = MyStudents.OrderBy(s => s.LastName).ThenBy(s=> s.FirstName);

note that OrderBy and ThenBy does not change the order of MyStudents list and they return an IEnumerable<Student>, so if you need a List<Student> use 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.