C # comparison and sorting (IComparable and IComparer and their generic implementations ),
Preparations:
1. Create an object class: ClassInfo, Which is sorted by the number of students in the class by default.
Public class ClassInfo
{
/// <Summary>
/// Class Name
/// </Summary>
Public string ClassName {get; set ;}
/// <Summary>
/// Number of Students
/// </Summary>
Public int StudentCount {get; set ;}
}
2. Insert the code in the Main method of the console Program
List <ClassInfo> classList = new List <ClassInfo> ();
ClassList. Add (
New ClassInfo ()
{
ClassName = "First Class ",
StudentCount = 40
});
ClassList. Add (new ClassInfo ()
{
ClassName = "Second Class ",
StudentCount = 39
});
Foreach (var o in classList ){
Console. WriteLine (string. Format ("{0 }:{ 1}", o. ClassName, o. StudentCount ));
}
Console. ReadKey ();
After running, it is displayed in the order of adding objects.
3. Try to Sort objects using the default Sort
ClassList. Sort ();
Error message: at least one object must be implemented as IComparable. So how can we sort custom object classes? The following is a one-to-one statement.
Basic Concepts
Comparison: compare two object classes by>, =, <.
Sort: In the collection class, sort the objects in the Collection class. The sort-based algorithm is based on the comparison function provided by the entity class.
C # provides default comparison and sorting algorithms for basic types. However, for entity classes with complicated structures, You need to implement the comparison and sorting methods by yourself.
1. IComparer
In the ClassInfo class, inherit the IComparer (IComparable <ClassInfo>) interface and implement the CompareTo method in the interface.
Public int CompareTo (ClassInfo o)
{
Return StudentCount. CompareTo (o. StudentCount );
}
Run, it is found that the display is in ascending order according to the number of students.
Note that the CompareTo method in the code above uses the default integer comparison method. The following custom code can be used to clarify the working principle of the comparator.
If (StudentCount> o. StudentCount)
Return 1;
Else if (StudentCount = o. StudentCount)
Return 0;
Else
Return-1;
2. IComparer: Use IComparer to implement a custom Comparator
Public class SortByName: IComparer <ClassInfo>
{
Public int Compare (ClassInfo x, ClassInfo y)
{
Return x. ClassName. CompareTo (y. ClassName );
}
}
In Main (), change classList. Sort () to classList. Sort (new SortByName ());
After running, the data in the set is sorted by name.
3. Use the lamda expression for comparative sorting:
ClassList. Sort (ClassInfo obj1, ClassInfo obj2) =>{ return obj1.ClassName. CompareTo (obj2.ClassName );});