views:

51

answers:

5

i have a class called student, the class have two elements (Name, ID). in my main class, i have created about 10 students in an array i called it students,

now i want to sort the the students array respecting the ID, or the name!!

if i used this line of code

array.sort(students);

is there a way to use the sort method and choose which element i want to sort the array with???

+1  A: 

You could use something like this:

Array.Sort(array, (s1, s2) => s1.Name.CompareTo(s2.Name));

You can define the comparator function however you want to get different sorting orders.

bde
thanx man!!, the easy and the most beautiful way :D:D:D:D:DD
Nadeem
i have a question, how i can choose which indices in the array i want to sort?
Nadeem
That's a good question. I think you would either have to extract a subset of the array and sort that, or have your student class implement IComparable and then pass the starting index and length to Array.Sort(). It doesn't look like there is a overload of Array.Sort() that allows you to specify start index and length as well as an inline comparison function. You could also ask that as a new SO question, someone else might have a good idea.
bde
A: 

I would use a list for this.

List<Student> students = new List<Student>{ new Student(), new Student(), new Student() }

then sort that list with LINQ

var sortedStuds = students.OrderBy(s => s.ID).ToList();

where the s is a Student object

EJC
Unnecessarily inefficient. `List<T>` has a `Sort` method that sorts in-place. (And so does `Array.Sort`.)
Timwi
true, but I didn't know efficiency was a problem. BTW I was going to use `Sort`, but I used it somewhere else and got fussed at for it. And I just like List<T> :)
EJC
A: 

you can use linq:

sortedStudents1 = students.OrderBy(s=>s.Name).ToList();
sortedStudents2 = students.OrderBy(s=>s.ID).ToList();
Danny Chen
+1  A: 

If it’s an array, the most efficient way is to use Array.Sort:

Array.Sort(array, (s1, s2) => s1.Name.CompareTo(s2.Name));
Timwi
A: 

While I also prefer the LINQ solution, you could alternatively make your Student class implement IComparable, which could give you more complex sorting options without having to write an in-line function every time.

stefan_g