您的位置:首页 > 编程语言 > C#

C#_IComparable实例 - 对象ID进行排序

2013-09-10 00:52 465 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComparableTest
{
class Program
{
class Employee : IComparable<Employee>
{
private int empID;

public Employee(int empID)
{
this.empID = empID;
}

public override string ToString()
{
return empID.ToString();
}

public bool Equals(Employee other)
{
if (this.empID == other.empID)
{
return true;
}
else
{
return false;
}
}

public int CompareTo(Employee rhs)
{
return this.empID.CompareTo(rhs.empID);
}
}

static void Main(string[] args)
{
List<Employee> le = new List<Employee>();
Random random = new Random();

for (int i = 0; i < 5;i++ )
{
le.Add(new Employee(random.Next(10)+100));
}

for (int i = 0; i<le.Count; i++)
{
Console.Write(le[i].ToString()+",");
}

Console.WriteLine();
Console.WriteLine("after sort");

le.Sort();
for (int i = 0; i < le.Count; i++)
{
Console.Write(le[i].ToString() + ",");
}

Console.ReadLine();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#