C # comparison and sorting (IComparable and IComparer and their generic implementations ),

Source: Internet
Author: User
Tags sorted by name

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 );});

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.