List<T>.sort() can realize the sorting of T. For example, after List<int>.sort() is executed, the collection will be sorted from small to large according to int. If T is a custom Object, but we want to sort it in our own way, what should we do? In fact, we can use the IComparable interface to rewrite the CompareTo method to achieve it. The process is as follows:
1. The first step is to declare a class Person but inherit the IComparable interface:
using System;
using ;
using ;
using ;
using ;
namespace TestIComparable
{
public class Person : IComparable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Person obj)
{
int result;
if ( == && == )
{
result = 0;
}
else
{
if (() > 0)
{
result = 1;
}
else if ( == && > )
{
result = 1;
}
else
{
result = -1;
}
}
return result;
}
public override string ToString()
{
return + "-" + ;
}
}
}
2. Then call the sort method in the main function. The classes will be sorted from childhood to adult by name. If the names are the same, they will be sorted from childhood to adult by age.
public class Program
{
public static void Main(string[] args)
{
List<Person> lstPerson = new List<Person>();
(new Person(){ Name="Bob",Age=19});
(new Person(){ Name="Mary",Age=18});
(new Person() { Name = "Mary", Age = 17 });
(new Person(){ Name="Lily",Age=20});
();
();
}
}
3. If the IComparable interface is not inherited, how should we implement sorting? It can be implemented using Linq. In fact, the effect is the same, but if the collection of classes needs to be sorted frequently, it is recommended to use the inheritance interface method, which can simplify the sort code and make it easier for people to understand.
public static void Main(string[] args)
{
List<Person> lstPerson = new List<Person>();
(new Person(){ Name="Bob",Age=19});
(new Person(){ Name="Mary",Age=18});
(new Person() { Name = "Mary", Age = 17 });
(new Person(){ Name="Lily",Age=20});
((x,y) =>
{
int result;
if ( == && == )
{
result = 0;
}
else
{
if (() > 0)
{
result = 1;
}
else if ( == && > )
{
result = 1;
}
else
{
result = -1;
}
}
return result;
});
();
}