SoFunction
Updated on 2025-03-08

C# basic array sorting and object size comparison implementation code

Start with a small example:
Copy the codeThe code is as follows:

int[] intArray = new int[]{2,3,6,1,4,5};
(intArray);
<int>(intArray,(i)=>(i));

This example defines an int array, then sorts the array using (arr) static method, and finally outputs the sorted array. The above examples will output 1, 2, 3, 4, 5, 6 in sequence without any surprise.
Why can Array's Sort method correctly sort the int array? Can we customize the class? Try it, as follows:
Copy the codeThe code is 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="Zhang San",Score=70},
new Student(){Age = 12,Name="Li Si",Score=97},
new Student(){Age = 11,Name="Wang Wu",Score=80},
new Student(){Age = 9,Name="Zhao Liu",Score=66},
new Student(){Age = 12,Name="Sima",Score=90},
};
("--------------------------------------------------------------);
(students);
<Student>(students,(s)=>(("{0}{1,2} is old, his score is {2,3}",,,)));
();
}

We define the Student class and then sort its arrays. The program compiles correctly, but an error occurred. The runtime exception was thrown: {"Failed to compare two elements in the array."}. The InnerException of this exception is ArgumentException{"At least one object must implement IComparable."}; Runtime exception description: To use (arr) the static method, we must ensure that there is an element in the array to implement the IComparable interface. In this case, let the Student class implement the IComparable interface.
Copy the codeThe code is 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 and use Age for comparison
/// </summary>
/// <param name="obj">Compare objects</param>
/// <returns>Compare results</returns>
public int CompareTo(object obj)
{
if (obj is Student)
{
return (((Student)obj).Age);
}
return 1;
}
}

The IComparable interface is implemented in the Student class, and the Age attributes of Student are compared in the CompareTo method. This time, the program compiles and runs again. The program normally outputs the Student array sorted by age.
What if we want to sort the Score attributes of Student? The IComparable interface implemented by the Student class can only be sorted by one attribute.
This is very easy to implement.net's class library developers have prepared another interface for us. IComparer<T> interface to implement two instances of comparison type T. The StudentScoreComparer class below implements the IComparer<Student> comparison of Students according to Score attributes
Copy the codeThe code is as follows:

public class StudentScoreComparer : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return ();
}
}

Now we can use the following code to sort the Student array by Score attribute:
Copy the codeThe code is as follows:

("------------------------------------------------------------------------------);
(students, new StudentScoreComparer());
<Student>(students, (s) => (("{0}{1,2} is old, his score is {2,3}", , , )));

But is it a little bit like a simple sorting according to Score attributes and then defining a class? Is there a better way? Of course there is. .net prepares a delegate that compares the object size for us Comparison<T> We can use the Ramda expression or anonymous delegate to directly sort it, as follows:
Copy the codeThe code is as follows:

("---------------------------------------------------------------------);
(students, (s1, s2) => ());
<Student>(students, (s) => (("{0}{1,2} is old, his score is {2,3}", , , )));

The complete code example is as follows:
Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;
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 and use Age for comparison
/// </summary>
/// <param name="obj">Compare objects</param>
/// <returns>Compare results</returns>
public int CompareTo(object obj)
{
if (obj is Student)
{
return (((Student)obj).Age);
}
return 1;
}
}
static void Main(string[] args)
{
Student[] students = new Student[]{
new Student(){Age = 10,Name="Zhang San",Score=70},
new Student(){Age = 12,Name="Li Si",Score=97},
new Student(){Age = 11,Name="Wang Wu",Score=80},
new Student(){Age = 9,Name="Zhao Liu",Score=66},
new Student(){Age = 12,Name="Sima",Score=90},
};
("--------------------------------------------------------------);
(students);
<Student>(students, (s) => (("{0}{1,2} is old, his score is {2,3}", , , )));
("------------------------------------------------------------------------------);
(students, new StudentScoreComparer());
<Student>(students, (s) => (("{0}{1,2} is old, his score is {2,3}", , , )));
("---------------------------------------------------------------------);
(students, (s1, s2) => ());
<Student>(students, (s) => (("{0}{1,2} is old, his score is {2,3}", , , )));
();
}
public class StudentScoreComparer : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return ();
}
}
}
}

Summarize:
There are three interfaces for comparing object sizes in C#, namely IComparable, IComparable<T> and IComparer<T>. IComparable and IComparable<T> are behavior definitions that compare sizes between instances implemented by the class itself. IComparer<T> defines the behavior of specifically comparing the size of two T-type objects outside the comparison class. In addition, there is a delegate definition for comparison. Comparison<T> allows us to use Ramda expressions or anonymous delegates or methods to sort more conveniently.