C # Sort Comparison

Source: Internet
Author: User

As with C #, which defines the equality comparison specification, C # also defines a sort comparison specification to determine the order in which an object and another object are sequenced. The sorting specification is as follows

    • IComparable interface (includes IComparable interface and icomparable<t> interface)
    • > and < Operators

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

String[] colors={"Green", "Red", "Blue"}; Array.Sort (colors) foreach (string C in colors)    Console.Write (c+ "");

The < and > operators are special because they are generally used to compare numeric types. Because the greater-than and less-than operators are parsed statically, they "produce" efficient code that works well for complex computing scenarios.

The. NET Framework also provides a plug-in sort protocol--icomparer interface. The difference between the IComparable interface and the IComparer interface is similar to the iequatable and IEqualityComparer interfaces (refer to C # Equality for iequtable interfaces and IEqualityComparer interfaces: http ://www.cnblogs.com/yang_sy/p/3582946.html)

1. IComparable interface

The IComparable interface is defined as follows

public interface IComparable    int CompareTo (Object obj);} public interface icomparable<in t>{    int CompareTo (T);}

The two interfaces define the same functionality. For value types The,icomparable<t> interface is more efficient than the Icompare interface. The CompareTo method of the above two interfaces is run as follows:

    • If A is behind B, then A.compareto (b) returns 1
    • If a and not the same, then return 0
    • If a is not in front, then return-1

Let's look at the following sample code:

ilist<staff> staffs = new List<staff> {    new staff{firstname= "AAA", title= "Manager", dept= "Sale"},      New Staff{firstname= "BBB", title= "Accountant", dept= "Finance"},    new Staff{firstname= "CCC", title= "Accountant", Dept= "Finance"},}; Console.WriteLine ("BBB"). CompareTo (Staffs[0]. FirstName)); 1console.writeline ("BBB"). CompareTo (Staffs[1]. FirstName)); 0console.writeline ("BBB"). CompareTo (Staffs[2]. FirstName)); -1

Most of C # 's basic types implement the IComparable interface and the Icomparable<t> interface. Many custom types also implement the interface, which makes it easy to sort.

Icomarable and equals

Suppose a type overrides the Equals method and implements the IComparable interface. Then you must hope that when equals returns True, CompareTo should return 0. When Equals returns False, CompareTo can return any value.

In other words, equality is stricter than contrast, and vice versa. Therefore, when CompareTo says "two objects are equal", equals says "These two objects are not necessarily equal". A good example is from the System.String class. The String.Equals method and the = = Operator Use ordinal collation to compare strings-that is, to sort by the Unicode value of each character. The String.CompareTo method, however, uses a less restrictive culture-based region (Culture-dependent) for comparison. For most computers, the characters disables and?, Equals returns False, and CompareTo returns 0

You can implement a specific sorting algorithm by IComparer the interface. The implementation of the custom IComparer interface further increases the difference between the CompareTo and the Equals method. For example, case-insensitive string comparators, for a and a, will return 0. This also proves from the opposite side that the Comparto method is not as strict as the Equals method.

2. < and > Operators

Some types that define the < and > operators, such as:

BOOL after2010 = datetime.now > New DateTime (2010, 1, 1); Console.WriteLine (after2010);

After implementing the < and > operators, you need to ensure that the < and > operators are consistent with the IComparable interface. This is also the standard for the. NET Framework.

Similarly, when a type overloads the < and > operators, it is also required to implement the IComparable interface, and vice versa. In fact, most. NET type implements the IComparable interface and does not overload the < and > operators. This (sort comparison) is not the same as equality:

    • If the Equals method is overloaded when implementing equality comparisons, the = = operator is generally overloaded
    • In order to achieve a sort comparison, if the CompareTo method is implemented, overloading < operators and > operators are generally not required

In general, you need to overload the < operator and the > operator only in the following scenario:

    • A type itself contains a concept that is greater than and less than this
    • The way to perform sequential comparisons is unique
    • Results do not change with cultural regions (cultures)

The system.stirng type does not satisfy the last bar, so string does not support > Operations and < operations. So "Beck" > "Anne" will throw an error at compile time.

3. Implement the IComparable interface

In the following instance code, the structure note represents a musical annotation that implements the IComparable interface and also overloads the < operator and the > operator. For instance integrity, we've also rewritten the Equals and GetHashCode methods, as well as overloading the = = and! = operators, and with this example, you can get a comprehensive look at sorting comparisons.

Internal struct note:icomparable, Icomparable<note>, iequatable<note>{private int semitonesfroma;    public int Semitonesfroma {get {return semitonesfroma;}    } public Note (int semitonesfroma) {this.semitonesfroma = Semitonesfroma; }//generic icomparable<t> public int CompareTo (Note other) {if (other)) return        0; Return Semitonesfroma.compareto (other.    Semitonesfroma); }//Non-generic icomaparable public int IComparable.CompareTo (object other) {if (! (        Other is note) throw new InvalidOperationException ("Compareto:not a note");    Return CompareTo (Note) other);    } public static BOOL operator < (note N1, note n2) {return N1.compareto (N2) < 0;    } public static BOOL operator > (note N1, note n2) {return N1.compareto (N2) > 0; }//For IEquatable public bool Equals (Note Other) {return this. SemitonesfrOmA = = Other.    Semitonesfroma; }//Override Object.Equals public override bool Equals (Object Other) {if (! (        Other is note) throw new InvalidOperationException ("Compareto:not a note");    Return Equals ((Note) other);    } public override int GetHashCode () {return semitonesfroma.gethashcode (); } public static bool operator = = (Note n1, note n2) {return N1.    Equals (N2); } public static bool operator! = (note n1, note n2) {return!    N1 = = N2); }}

C # Sort comparison

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.