In this program, you’ll learn to sort an ArrayList of custom object by their given property in C#.
In the below program, we’ve defined a Student class with a string and int properties, Name and Age. We’ve also added a constructor that initializes the properties.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Student { string name; int age; public Student(string name, int age) { Name = name; Age = age; } public string Name { get => name; set => name = value; } public int Age { get => age; set => age = value; } } |
And In Program class, I created a class that implements IComparer, and provide that.(icomparer C# Example)
1 2 3 4 5 6 7 8 9 10 11 | public class myComparer : IComparer { int IComparer.Compare(Object xx, Object yy) { Student x = (Student)xx; Student y = (Student)yy; return x.Age.CompareTo(y.Age); } } |
Finally ,I created the program class as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class Program { public class myComparer : IComparer { int IComparer.Compare(Object xx, Object yy) { Student x = (Student)xx; Student y = (Student)yy; //sort by age return x.Age.CompareTo(y.Age); } } static void Main(string[] args) { ArrayList myList=new ArrayList(); myList.Add(new Student("JAMES",31)); myList.Add(new Student("DAVID",25)); myList.Add(new Student("PAUL",45)); myList.Add(new Student("GEORGE",18)); myList.Add(new Student("LARRY",23)); //list before compared items Console.WriteLine("..::Before Sort::.."); foreach (Student item in myList) { Console.WriteLine("Name:{0} Age:{1}",item.Name,item.Age); } myList.Sort(new myComparer()); Console.WriteLine("\n..::After Sort::.."); foreach (Student item in myList) { Console.WriteLine("Name:{0} Age:{1}", item.Name, item.Age); } Console.ReadLine(); } } |
Output: