Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a List in C# [duplicate]

Tags:

c#

.net

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
like image 303
Leo Vo Avatar asked Jul 19 '10 07:07

Leo Vo


2 Answers

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();
like image 94
Mark Byers Avatar answered Sep 19 '22 16:09

Mark Byers


class Program
{
    static void Main(string[] args)
    {
        var list = new List<MyObject>(new[]
        {
            new MyObject { Name = "ABC", Age = 12 },
            new MyObject { Name = "BBC", Age = 14 },
            new MyObject { Name = "ABC", Age = 11 },
        });
        var sortedList = from element in list
                         orderby element.Name
                         orderby element.Age
                         select element;

        foreach (var item in sortedList)
        {
            Console.WriteLine("{0} {1}", item.Name, item.Age);
        }
    }
}
like image 35
Darin Dimitrov Avatar answered Sep 17 '22 16:09

Darin Dimitrov