C#中list.sort方法的使用 30
下面的这个程序实现了按ID排序,现在要加入代码,实现可以选择按ID、姓名等排序,请问怎么改?classProgram{staticvoidMain(string[]arg...
下面的这个程序实现了按ID排序,现在要加入代码,实现可以选择按ID、姓名等排序,请问怎么改?
class Program
{
static void Main(string[] args)
{
List<Employee> aList = new List<Employee>();
aList.Add(new Employee(2, "Li", "Net"));
aList.Add(new Employee(3, "Yu", "Net"));
aList.Add(new Employee(1, "Liu", "Data"));
aList.Add(new Employee(5, "Jia", "Soft"));
aList.Add(new Employee(4, "Jiang", "Train"));
aList.Sort();//使用CompareTo进行排序
//逐个从列表中取出每一个对象
foreach (Employee iItem in aList)
{
Console.WriteLine("ID:{0}, Name:{1}, Department:{2}", iItem.ID, iItem.name, iItem.department);
}
}
}
public class Employee : IComparable
{
public int ID;
public string name;
public string department;
public Employee(int iID, string sName, string sDepartment)
{
ID = iID;
name = sName;
department = sDepartment;
}
public int CompareTo(object obj)
{
if (obj is Employee)
{
Employee anotherEmployee = obj as Employee;
return this.ID - anotherEmployee.ID;
}
throw new ArgumentException("object is not a Employee");
}
} 展开
class Program
{
static void Main(string[] args)
{
List<Employee> aList = new List<Employee>();
aList.Add(new Employee(2, "Li", "Net"));
aList.Add(new Employee(3, "Yu", "Net"));
aList.Add(new Employee(1, "Liu", "Data"));
aList.Add(new Employee(5, "Jia", "Soft"));
aList.Add(new Employee(4, "Jiang", "Train"));
aList.Sort();//使用CompareTo进行排序
//逐个从列表中取出每一个对象
foreach (Employee iItem in aList)
{
Console.WriteLine("ID:{0}, Name:{1}, Department:{2}", iItem.ID, iItem.name, iItem.department);
}
}
}
public class Employee : IComparable
{
public int ID;
public string name;
public string department;
public Employee(int iID, string sName, string sDepartment)
{
ID = iID;
name = sName;
department = sDepartment;
}
public int CompareTo(object obj)
{
if (obj is Employee)
{
Employee anotherEmployee = obj as Employee;
return this.ID - anotherEmployee.ID;
}
throw new ArgumentException("object is not a Employee");
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询