List< T > 集合对复杂类型的排序Sort()有4个重载
1.T类型实现了IComparable< T >接口
2.另写一个类,该类实现了IComparer< T >
3.Sort(Comparison< T > comparison),Comparison< T >为一个委托类型,CSDN定义如下:
public delegate int Comparison< T >(T x ,T y);
// 摘要:
// 表示比较同一类型的两个对象的方法。
//
// 参数:
// x:
// 要比较的第一个对象。
// y:
// 要比较的第二个对象。
// 类型参数:
// T:
// 要比较的对象的类型。
// 返回结果:
// 一个有符号整数,指示 x 与 y 的相对值,如下表所示。 值 含义 小于 0 x 小于 y。 0 x 等于 y。 大于 0 x 大于 y。
实现第三种方法的实现有3种途径:
1.定义一个方法,定义一个委托实例,将该委托实例传入Sort()中
eg.
class Program
{
static void Main(string[] args)
{
Student sa1 = new Student(1, "Washington", 33);
Student sa2 = new Student(2, "Brown", 32);
Student sa3 = new Student(4, "Wade", 67);
Student sa4 = new Student(6, "Bosh", 47);
List list = new List (){sa1 ,sa2 ,sa3 ,sa4 };
Comparison comparison = new Comparison(SortByAge);//将方法传给委托实例
list.Sort(comparison);//将委托传入Sort()
}
//定义一个委托类型方法
static int SortByAge(Student x,Student y)
{
return x.Age.CompareTo(y.Age);
}
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Type { get; set; }
public Student(int id, string name, int age)
{
this.ID = id;
this.Name = name;
this.Age = age;
}
}
2.使用匿名委托
eg.
class Program
{
static void Main(string[] args)
{
Student sa1 = new Student(1, "Washington", 33);
Student sa2 = new Student(2, "Brown", 32);
Student sa3 = new Student(4, "Wade", 67);
Student sa4 = new Student(6, "Bosh", 47);
List list = new List (){sa1 ,sa2 ,sa3 ,sa4 };
//匿名委托delegate(Student x, Student y){return x.Name.CompareTo(y.Name);}
list.Sort(delegate(Student x, Student y){return x.Name.CompareTo(y.Name);});
}
static int SortByAge(Student x,Student y)
{
return x.Age.CompareTo(y.Age);
}
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Type { get; set; }
public Student(int id, string name, int age)
{
this.ID = id;
this.Name = name;
this.Age = age;
}
}
3.使用Lambda表达式
eg.
class Program
{
static void Main(string[] args)
{
Student sa1 = new Student(1, "Washington", 33);
Student sa2 = new Student(2, "Brown", 32);
Student sa3 = new Student(4, "Wade", 67);
Student sa4 = new Student(6, "Bosh", 47);
List list = new List (){sa1 ,sa2 ,sa3 ,sa4 };
//lambda表达式
list.Sort((x,y) => x.ID.CompareTo(y.ID));
foreach (Student s in listA )
{
Console.WriteLine(s.ID +" " + s.Name + " " + s.Age );
}
}
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Type { get; set; }
public Student(int id, string name, int age)
{
this.ID = id;
this.Name = name;
this.Age = age;
}
}