Alex Rivera | Logout

Sort with two criteria, string ascending, int ascending

Asked 2010-03-04T03:08:04.470
17

How can I perform a sort on two different criteria?

For example, I have person objects like:

Person with properties FirstName (string), LastName, and Rank (int).

Example data like so:

Xavier    Smith 1
Alexander Smith 2
Alexander Smith 1
Bob       Hawke 2

It should sort on FirstName alphabetically, then on rank, e.g. resulting:

Alexander Smith 1
Alexander Smith 2
Bob       Hawke 2
Xavier    Smith 1

So far, I have tried the following, but it isn't working properly:

peopleList is List<Person>

peopleList.Sort(new Comparison<Person>((x,y) => x.Rank.CompareTo(y.Rank)));
peopleList.Sort(new Comparison<Person>((x, y) => string.Compare(x.Name, y.Name)));

Thanks

edit: to avoid changing my code too much, I really want to keep list, if I change the above lines to:

peopleList.OrderBy(person => person.FirstName).ThenBy(person => person.Rank).ToList();

Would give the exact same list just sorted properly, correct?

Edit
Report

1 Answer

4

I like the LINQ answer. If that's not an option, you could always use

(x,y) => 2*string.Compare(x.Name,y.Name) + x.Rank.CompareTo(y.Rank)

so that the string compare always dominates unless it equals 0

answered 2010-03-04T03:24:25.053

Your Answer