Nadeem
Nadeem

Reputation: 385

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

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

Upvotes: 0

Views: 793

Answers (5)

stefan_g
stefan_g

Reputation: 57

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.

Upvotes: 0

WildCrustacean
WildCrustacean

Reputation: 5966

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.

Upvotes: 1

Timwi
Timwi

Reputation: 66584

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

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

Upvotes: 1

Cheng Chen
Cheng Chen

Reputation: 43523

you can use linq:

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

Upvotes: 0

EJC
EJC

Reputation: 2141

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

Upvotes: 1

Related Questions