Alex Rivera | Logout

How to sort a List in C#

Asked 2010-07-19T07:03:12.750
15

I have a class:

public class MyObject
{
public string Name;
public int Age;
}

I have a List of Myobject objects:

Name Age
ABC 12
BBC 14
ABC 11

How to sort this list with condition: sort Name first & sort Age later. With this list, the result after sorting:

Name Age
ABC 11
ABC 12
BBC 14
Edit
Report

1 Answer

14

Two different ways using LINQ:

1) Using OrderBy and ThenBy:

l = l.OrderBy(x => x.Name).ThenBy(x => x.Age).ToList();

2) Using the query syntax:

l = (from x in l
     orderby x.Name, x.Age
     select x).ToList();
answered 2010-07-19T07:07:56.327

Your Answer