views:

932

answers:

9

Hi,

Say I have a Person class with Name, Age, Level properties.

I know how to order by one of the properties, with

        PersonList.Sort(delegate(Person p1, Person p2) {
            return p1.Name.CompareTo(p2.Name);
        });

But how can I order by Name, Age and Level.

An equivalente of the sql sentence : ORDER BY Name, Age, Level

Thank you

+19  A: 

Adapting your current code:

PersonList.Sort(delegate(Person p1, Person p2) {
        int r = p1.Name.CompareTo(p2.Name);
        if (r == 0) r = p1.Age.CompareTo(p2.Age);
        if (r == 0) r = p1.Level.CompareTo(p2.Level);
        return r;
    });

or, a simple linq-ish solution:

PersonList = PersonList.OrderBy(p => p.Name)
                       .ThenBy(p => p.Age)
                       .ThenBy(p => p.Level).ToList();
Joel Coehoorn
Thanks for the fix, Marc. I realized my mistake, but the internet is being flaky and I was having trouble editing it.
Joel Coehoorn
Ah good, you edited it. Chaining OrderBys doesn't work :)
Thorarin
Good !!! Being on .Net 2.0 the very first solution works perfectly.King regards.
+2  A: 

I would implment IComparable on your Person class. In your custom compare method, you can set the logic to compare on all three properties, and make sure the three have the proper "weight" (e.g., if two instances of Person have the same name, should you sort next on Age or Level).

AllenG
+2  A: 

Have you considered switching to .NET 3.5 and using LINQ? Things like this are really easy in LINQ:

personList = personList.OrderBy(p => p.Name).
 ThenBy(p => p.Age).ThenBy(p => p.Level).ToList();
Thorarin
+1  A: 

Assuming you are using .NET 3.5

 IQueryable<Person> people = PersonList.AsQueryable();

 return people.OrderBy(x => x.Name).ThenBy(x => x.Age).ThenBy(x => x.level);
Kirschstein
A: 

If you have C# 3.0 available (LINQ support), then you can do the following:

var result = (from p in PersonList
              orderby p.Name, p.Age, p.Level
              select p).ToList();
Noldorin
A: 

Have you considered LINQ to Objects?

var x = (from p in PersonList
        orderby p.Name, p.Age, p.Level
        select p).ToList();
Scott Anderson
A: 

You need to call CompareTo on the first property you want to order by, get the value that is returned, and if it is 0, then call CompareTo on the next property, and repeat, each time 0 is returned, continue onto the next property until you get a non-zero value (which you then return) or you get to the end of the properties you want to sort by.

Simon P Stevens
A: 
var result = from p in persons
             orderby p.Name, p.Age, p.Level
             select p;
frameworkninja
A: 

Thank you for all the rapid answers.

My mistake for no having spcecified it was for .Net 2.0.