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
MarJamRob
  • 3,395
  • 7
  • 22
  • 31
Leo Vo
  • 9,980
  • 9
  • 56
  • 78
  • I have another question at here: http://stackoverflow.com/questions/3279248/help-me-to-combine-sorting-filtering-on-a-list – Leo Vo Jul 19 '10 at 07:46

5 Answers5

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();
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
10
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);
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

Using System.Linq you can acheive it easily:

list = list.OrderBy(e=>e.Name).ThenBy(e=>e.Age);

Also check this answer: Sorting a list using Lambda/Linq to objects.

Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

You can do the following using LINQ:

class Program
{
    static void Main(string[] args)
    {
        List<MyObject> list = new List<MyObject>();

        list.Add(new MyObject() { Age = 12, Name = "ABC" });
        list.Add(new MyObject() { Age = 11, Name = "ABC" });
        list.Add(new MyObject() { Age = 14, Name = "BBC" });

        var sorted = list.OrderBy(mo => mo.Name).ThenBy(mo => mo.Age);

        foreach (var myObject in sorted)
        {
            Console.WriteLine(string.Format("{0} - {1}",
                              myObject.Name, myObject.Age));
        }
    }
}
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
0

You can pass an new Object to Order By so that it Orders By that

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 = list.OrderBy( x => new { x.Name , x.Age });

        foreach (var item in sortedList)
        {
            Console.WriteLine("{0} {1}", item.Name, item.Age);
        }
    }
}
Vignesh Murugan
  • 575
  • 5
  • 18