I want to sort data by the alphabet. I implemented IComparer<> into my class, and also overwritten the Compare Method. My Question now is how I can use this method?
Asked
Active
Viewed 83 times
0
-
1Share your code please... – MD. RAKIB HASAN Jul 27 '21 at 07:07
-
It is better not to put the sort into an existing class but make it a separated class. You need to create a constructor for the list so the comparison works and then use the linq OrderBy to do the sort. – jdweng Jul 27 '21 at 07:09
-
Does this answer your question? [Using IComparer for sorting](https://stackoverflow.com/questions/14336416/using-icomparer-for-sorting) and [Using IComparer
.Compare(T,T) in C#](https://stackoverflow.com/questions/27597770/using-icomparert-comparet-t-in-c-sharp) and [How to implement IComparer in C# for an interface](https://stackoverflow.com/questions/16474668/how-to-implement-icomparer-in-c-sharp-for-an-interface) – Jul 27 '21 at 07:53
1 Answers
1
All what you need is to call on Array.Sort() giving it the array to be sorted and the an instance of your custom comparer class. Here's an example:
public class Car {
...
}
public class CarComparer : IComparer<Car> {
public int Compare(Car x, Car y) {
...
}
}
public static void Main(string[] args) {
var cars = new Car[] { ... };
var carComparer = new CarComparer();
Array.Sort(cars, carComparer);
}

Mohammed Ezzedine
- 56
- 7