C#对实例进行排序方法
样例:对实例的某个属性进行排序,从而对实例进行排序。

student.cs
namespace winform
{
public class student:IComparable<student>
{
public student(string name,int age,string id)
{
this.Age = age;
this.Id = id;
this.Name1 = name;
}
public int Age { get; set; }
public string Name1 { get; set; }
public string Id { get; set; }
public int CompareTo(student other)
{
return other.Age.CompareTo(this.Age);
}
}
public class Asc : IComparer<student>
{
public int Compare(student x, student y)
{
return x.Age.CompareTo(y.Age);
}
}
}
form1.cs
namespace winform
{
public partial class Form4 : Form
{
List<student> students;
public Form4()
{
InitializeComponent();
define();
students.Sort();
this.dgvlist.DataSource = this.students;
}
private void define()
{
this.students = new List<student>();
student stuzs = new student("张三", 32, "1992235");
student stuls = new student("李四", 34, "1994545");
student stuww = new student("王五", 34, "1892235");
students.Add(stuzs);
students.Add(stuls);
students.Add(stuww);
}
//默认排序
private void showall_Click(object sender, EventArgs e)
{
students.Sort();
this.dgvlist.DataSource = students;
this.dgvlist.Refresh();
}
//升序排序
private void Agease_Click(object sender, EventArgs e)
{
this.students.Sort(new Asc());
this.dgvlist.Refresh();
this.dgvlist.DataSource = this.students;
}
}