C#对实例进行排序方法

C基础算法 fkwebs 5年前 (2015-11-06) 2545次浏览 已收录 0个评论

C#对实例进行排序方法

样例:对实例的某个属性进行排序,从而对实例进行排序。
QQ截图20151106101804

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;
 }
}

CyanProbe , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C#对实例进行排序方法
喜欢 (1)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址