C # Basics of array sorting, object size comparison implementation Code _c# tutorial

Source: Internet
Author: User
Starting from a small example:
Copy Code code as follows:

int[] Intarray = new int[]{2,3,6,1,4,5};
Array.Sort (Intarray);
Array.foreach<int> (Intarray, (i) =>console.writeline (i));

This example defines an array of int and then sorts the array using the Array.Sort (arr) static method, and finally outputs the sorted array. The above example will output 1,2,3,4,5,6 in turn without exception.
Why is the array's sort method able to correctly sort the array of int, can we customize the class? Try the following code:
Copy Code code as follows:

public class Student
{
public int Age {get; set;}
public string Name {get; set;}
public int Score {get; set;}
}
static void Main (string[] args)
{
Student[] Students = new student[]{
New Student () {age = 10,name= "John", score=70},
New Student () {age = 12,name= "Dick", score=97},
New Student () {age = 11,name= "Harry", score=80},
New Student () {age = 9,name= "Zhao Liu", score=66},
New Student () {age = 12,name= "Sima", score=90},
};
Console.WriteLine ("--------------default sort Output--------");
Array.Sort (students);
Array.foreach<student> (students, (s) =>console.writeline (string. Format ("{0}{1,2} old, his score is {2,3}", S.name,s.age,s.score));
Console.read ();
}

We define the student class and then sort his array, the program compiles correctly, but the run goes wrong, and the runtime throws an exception: system.invalidoperationexception{"Failed to compare two Elements in the array. "}, the innerexception of this exception is argumentexception{" at least one object must implement. "} , runtime exception Description: We need to use the Array.Sort (arr) static method, we must ensure that there is an element in the array to implement the IComparable interface. In that case we let the student class implement the IComparable interface.
Copy Code code as follows:

public class Student:icomparable
{
public int Age {get; set;}
public string Name {get; set;}
public int Score {get; set;}
<summary>
Implement IComparable interface, compare with age
</summary>
<param name= "obj" > Compare Objects </param>
<returns> comparison Results </returns>
public int CompareTo (object obj)
{
if (obj is Student)
{
Return Age.compareto ((Student) obj). Age);
}
return 1;
}
}

The IComparable interface is implemented in the student class, and the age attribute of student is compared in the CompareTo method, which is compiled again and again, and the program normally outputs an array of student in chronological order.
What if we were to sort the score attributes of student? The IComparable interface implemented by the student class can only be sorted by one attribute.
This is easy to implement. NET's class library developer has already prepared another interface icomparer<t> interface to implement the two instances of the comparison type T. The following Studentscorecomparer class implements a comparison of Student according to the score property icomparer<student>
Copy Code code as follows:

public class Studentscorecomparer:icomparer<student>
{
public int Compare (Student x, Student y)
{
Return X.score.compareto (Y.score);
}
}

Now we can sort the student array by the Score property using the following code:
Copy Code code as follows:

Console.WriteLine ("----------sorted output------------by fractions");
Array.Sort (students, New Studentscorecomparer ());
Array.foreach<student> (students, (s) => Console.WriteLine (String. Format ("{0}{1,2} years old, his score is {2,3}", S.name, S.age, S.score));

But a simple to sort by score attribute, and then define a class is not a little big problem, there is no better way? Of course. . NET prepares us for a delegate that compares the size of objects comparison<t> we can use lambda expressions or anonymous delegates to sort directly, following code implementation:
Copy Code code as follows:

Console.WriteLine ("----------sorted output----------by fractions");
Array.Sort (students, S1, S2) => s1.Score.CompareTo (S2. Score));
Array.foreach<student> (students, (s) => Console.WriteLine (String. Format ("{0}{1,2} years old, his score is {2,3}", S.name, S.age, S.score));

The complete code example is as follows:
Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Namespace Sortingincsharp
{
Class Program
{
public class Student:icomparable
{
public int Age {get; set;}
public string Name {get; set;}
public int Score {get; set;}
<summary>
Implement IComparable interface, compare with age
</summary>
<param name= "obj" > Compare Objects </param>
<returns> comparison Results </returns>
public int CompareTo (object obj)
{
if (obj is Student)
{
Return Age.compareto ((Student) obj). Age);
}
return 1;
}
}
static void Main (string[] args)
{
Student[] Students = new student[]{
New Student () {age = 10,name= "John", score=70},
New Student () {age = 12,name= "Dick", score=97},
New Student () {age = 11,name= "Harry", score=80},
New Student () {age = 9,name= "Zhao Liu", score=66},
New Student () {age = 12,name= "Sima", score=90},
};
Console.WriteLine ("--------------default sort Output--------");
Array.Sort (students);
Array.foreach<student> (students, (s) => Console.WriteLine (String. Format ("{0}{1,2} years old, his score is {2,3}", S.name, S.age, S.score));
Console.WriteLine ("----------sorted output------------by fractions");
Array.Sort (students, New Studentscorecomparer ());
Array.foreach<student> (students, (s) => Console.WriteLine (String. Format ("{0}{1,2} years old, his score is {2,3}", S.name, S.age, S.score));
Console.WriteLine ("----------sorted output----------by fractions");
Array.Sort (students, S1, S2) => s1.Score.CompareTo (S2. Score));
Array.foreach<student> (students, (s) => Console.WriteLine (String. Format ("{0}{1,2} years old, his score is {2,3}", S.name, S.age, S.score));
Console.read ();
}
public class Studentscorecomparer:icomparer<student>
{
public int Compare (Student x, Student y)
{
Return X.score.compareto (Y.score);
}
}
}
}

Summarize:
There are three interfaces for comparing object sizes in C #, respectively, IComparable, icomparable<t>, and icomparer<t>. IComparable and icomparable<t> are definitions of behavior that the class itself implements to compare sizes between instances. Icomparer<t> is the behavior that defines the size of two T-type objects outside of the comparison class, plus a delegate definition for comparison comparison<t> lets us use lambda expressions or anonymous delegates or methods for easier sorting.

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.