C # sorting and Comparison

Source: Internet
Author: User

Similar to C #'s definition of equality comparison norms, C # also defines sorting comparison norms to determine the order of one object and another. The sorting rules are as follows:

  • IComparable interface (including the IComparable interface and IComparable <T> Interface)
  • > And <Operator

Use the IComparable interface to implement the sorting algorithm. In the following example, the static method Array. Sort can be called because the System. String class implements the IComparable interface.

[] colors={, , ( c +  );

The <and> operators are special because they are generally used to compare numeric types. Since operators greater than and less than are statically parsed, they "generate" efficient Code and are suitable for complex computing scenarios.

. NET Framework also provides the plug-in-type sorting protocol-IComparer interface. The differences between IComparable and IComparer interfaces are similar to those of IEquatable and IEqualityComparer (for more information about IEqutable and IEqualityComparer interfaces, see C # equality: http://www.cnblogs.com/yang_sy/p/3582946.html)

 

1. IComparable Interface

The IComparable interface is defined as follows:

   IComparable< T>

The two interfaces define the same functions. For value types, the IComparable <T> interface is more efficient than the ICompare interface. The CompareTo methods of the above two interfaces are run in the following way:

  • If a is placed behind B, a. CompareTo (B) returns 1
  • If a and a are different, 0 is returned.
  • If a is not ranked first,-1 is returned.

Let's take a look at the following sample code:

IList<Staff> staffs =  List<Staff> Staff{FirstName=, Title=, Dept= Staff{FirstName=, Title=, Dept= Staff{FirstName=, Title=, Dept=.CompareTo(staffs[].FirstName)); Console.WriteLine(.CompareTo(staffs[].FirstName)); Console.WriteLine(.CompareTo(staffs[].FirstName)); 

Most basic types of C # implement the IComparable interface and IComparable <T> interface. Many custom types also implement this interface to facilitate sorting.

IComarable and Equals

Assume that a type overrides the Equals method and implements the IComparable interface. So you certainly want CompareTo to return 0 when Equals returns true. When Equals returns false, CompareTo can return any value.

In other words, equality is more strict than contrast, but not vice versa. Therefore, when CompareTo says "two objects are equal", Equals will say "These two objects are not necessarily equal ". A good example is from the System. String class. The String. Equals method and the = Operator use the sequence number sorting rule to compare strings-that is, sort the strings by the Unicode values of each character. While the String. CompareTo method uses less strict comparison based on the cultural-dependent. For most computers, Equals returns False, while CompareTo returns 0.

You can use the IComparer interface to complete specific sorting algorithms. The implementation of the custom IComparer interface further increases the difference between the CompareTo and Equals methods. For example, for case-insensitive string comparator, 0 is returned for A and a. This also proves from the opposite side that the ComparTo method is not as strict as the Equals method.

 

2. <and> Operators

The <and> operators are defined for some types, such:

 after2010 = DateTime.Now >  DateTime(, , 

After the <and> operator is implemented, you must ensure that the <and> operator is consistent with the IComparable API. This is also the standard of. NET Framework.

Similarly, when a type reloads the <and> operators, the IComparable interface is also required, while the opposite is not required. In fact, most. NET types implement the IComparable interface and do not overload the <and> operators. This (sort comparison) is different from equality:

  • If the Equals method is overloaded when equality comparison is implemented, the = Operator is generally overloaded.
  • If the CompareTo method is implemented for sorting comparison, the <operator and> operator are not required to be overloaded.

Generally, the <operator and> operator must be overloaded only in the following scenarios:

  • A type contains the concepts of greater than or less
  • The method for comparing execution order is unique.
  • The results will not change with the cultural areas (Cultures)

The System. Stirng type does not meet the last one. Therefore, the string type does not support> operations and <operations. Therefore, "beck"> "Anne" will throw an error during compilation.

 

3. Implement the IComparable Interface

In the following example code, the structure Note represents a music comment, which implements the IComparable interface and also reloads the <operator and> operator. For instance integrity, we have also rewritten the Equals and GetHashCode methods, and overloaded the = and! = Operator. In this example, you can fully understand the sorting comparison.

  Note : IComparable, IComparable<Note>, IEquatable<Note>   {  Note(.semitonesFromA =            IComparable.CompareTo( (!(other   InvalidOperationException(    < n1.CompareTo(n2) <     > n1.CompareTo(n2) >       .SemitonesFromA ==       Equals( (!(other   InvalidOperationException(      ==    != !(n1 ==

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.