C # Note 25: Comparison and sorting (IComparable and IComparer and their generic implementations)

Source: Internet
Author: User

Summary:

1: Concepts of comparison and sorting;

2: IComparable and IComparer;

3: IComparable and IComparer generic implementation IComparable <T> and IComparer <T>;

 

1: Concepts of comparison and sorting

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.

The basic types all provide the default comparison algorithm. For example, string provides the comparison by letter, and int provides the comparison by integer size.

 

2: IComparable and IComparer

When we create our own entity classes, such as Student, we want to sort them by age by default, we need to implement the IComparable interface for the object class.

Class Student: IComparable
{
Public string Name {get; set ;}
Public int Age {get; set ;}

# Region IComparable Members

Public int CompareTo (object obj)
{
Student student = obj as Student;
If (Age> student. Age)
{
Return 1;
}
Else if (Age = student. Age)
{
Return 0;
}
Else
{
Return-1;
}
// Return Age. CompareTo (student. Age );
}
# Endregion
}


PS: note that the CompareTo method in the above Code has a annotated code. In fact, this function can be replaced by the annotated code, because the default comparison method of integer is used. This annotation code is not used here to better illustrate the working principle of the comparator. Next, write a test case: public Form1 ()
{
InitializeComponent ();
StudentList = new ArrayList ();
StudentList. Add (new Student () {Age = 1, Name = "a1 "});
StudentList. Add (new Student () {Age = 5, Name = "g1 "});
StudentList. Add (new Student () {Age = 4, Name = "b1 "});
StudentList. Add (new Student () {Age = 2, Name = "f1 "});
}
ArrayList studentList;
Private void button#click (object sender, EventArgs e)
{
StudentList. Sort ();
Foreach (Student item in studentList)
{
This. textBox1.Text + = item. Name + "----" + item. Age. ToString () + "";
}
}
Running result:

A1 ---- 1
F1 ---- 2
B1 ---- 4
G1 ---- 5

OK. The question is displayed. What should I do if I don't want to use age as the comparator. In this case, IComparer is used to implement a custom comparator. As follows:

Class SortName: IComparer
{
# Region IComparer Members

Public int Compare (object x, object y)
{
Student s1 = x as Student;
Student s2 = y as Student;
Return s1.Name. CompareTo (s2.Name );
}

# Endregion
}
In this case, we provide this comparator for the Sort method in sorting:

StudentList. Sort (new SortName ());

The running result is:

A1 ---- 1
B1 ---- 4
F1 ---- 2
G1 ---- 5

3: IComparable and IComparer generic implementation IComparable <T> and IComparer <T>

If we have a little experience, we will find that the above Code uses a collection class ArrayList that is not recommended. When generics are available, we recommend that you do not use all non-generic collection classes as much as possible. As for the reason, we can also see some clues from the above Code.

Check the Compare function, for example:

Public int Compare (object x, object y)
{
Student s1 = x as Student;
Student s2 = y as Student;
Return s1.Name. CompareTo (s2.Name );
}
 

We found that this function is packed and unpacked. This will affect the performance. If our set contains thousands of complex entity objects, the performance consumed during sorting is objective. The appearance of generics can avoid unpacking and packing.

Therefore, the ArrayList in the above Code should be replaced by List <T>. For the corresponding, we should implement IComparable <T> and IComparer <T>. The final code should be like:

Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
StudentList = new List <Student> ();
StudentList. Add (new Student () {Age = 1, Name = "a1 "});
StudentList. Add (new Student () {Age = 5, Name = "g1 "});
StudentList. Add (new Student () {Age = 4, Name = "b1 "});
StudentList. Add (new Student () {Age = 2, Name = "f1 "});
& Nb

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.