Sorting array of type of object respecting to one of the object values

794 views Asked by At

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???

5

There are 5 answers

2
WildCrustacean On BEST ANSWER

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.

2
EJC On

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

0
Cheng Chen On

you can use linq:

sortedStudents1 = students.OrderBy(s=>s.Name).ToList();
sortedStudents2 = students.OrderBy(s=>s.ID).ToList();
0
Timwi On

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

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

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.