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 开发者_Go百科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???
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.
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
If it’s an array, the most efficient way is to use Array.Sort
:
Array.Sort(array, (s1, s2) => s1.Name.CompareTo(s2.Name));
you can use linq:
sortedStudents1 = students.OrderBy(s=>s.Name).ToList();
sortedStudents2 = students.OrderBy(s=>s.ID).ToList();
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.
精彩评论