Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of objects by two criterias?

I have an array of objects that i want to sort by two keys. The objects lets say are of type Student and the properties that i'm intrested in for my sort are grade and name.

Student
{
    double grade;
    string name;
    ...
} 

How can i sort the objects first by grade and then by name? so for example if i have the list: Tom 9.9 Andrew 9.8 Chriestie 10 Mat 9.8 Allison 10 Ada 9.8

After the sort i should have: Allison 10 Christie 10 Tom 9.9 Ada 9.8 Andrew 9.8 Mat 9.8

And not Christie 10 Allison 10 Tom 9.9 Andrew 9.8 Ada 9.8 Mat 9.8

any pointer is really helpful.

like image 708
Sorin Antohi Avatar asked Jan 15 '10 13:01

Sorin Antohi


1 Answers

I'm pretty flakey on my objective-c knowledge but there's some good pointers here and there's always the documentation. Here's my crack at it...

NSSortDescriptor *gradeSorter = [[NSSortDescriptor alloc] initWithKey:@"grade" ascending:YES];
NSSortDescriptor *nameSorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

[personList sortUsingDescriptors:[NSArray arrayWithObjects:gradeSorter, nameSorter, nil]];
like image 97
Ajw Avatar answered Oct 27 '22 00:10

Ajw