C#中的IComparer接口
1前言
本文通过一个简单的例子,说明如何通过传递实现IComparer接口的类,对ArrayList集合中的元素按照自定义的排序逻辑进行排序。
2例子
2.1定义StudentInfo类
public class StudentInfo
{
public string id;//学号
public string name;//姓名
public string address;//家庭住址
public StudentInfo(string id, string name, string address)
{
this.id = id;
this.name = name;
this.address = address;
}
public void Show()
{
Console.WriteLine(id + ", " + name + ", " + address);
}
}
2.2定义实现IComparer接口类,该类对学生按照姓名进行降序排序
public class StudentNameCompare : IComparer
{
public int Compare(object x, object y)
{
return new CaseInsensitiveComparer().Compare(((StudentInfo)y).name,((StudentInfo)x).name);
}
}
2.3利用实现IComparer接口的类对学生信息进行排序
ArrayList arrayList = new ArrayList();
StudentInfo customer1 = new StudentInfo("Id002","王三","河南郑州市");
arrayList.Add(customer1);
StudentInfo customer2 = new StudentInfo("Id001","赵大","山东菏泽市");
arrayList.Add(customer2);
StudentInfo customer3 = new StudentInfo("Id003","钱二","湖北武汉市");
arrayList.Add(customer3);
Console.WriteLine("排序前的集合排列");
for (int i = 0; i < arrayList.Count; ++i)
{
StudentInfo customerInfoElement = (StudentInfo)arrayList[i];
customerInfoElement.Show();
}
Console.WriteLine("排序后的集合排列");
arrayList.Sort(new StudentNameCompare());
for (int i = 0; i < arrayList.Count; ++i)
{
StudentInfo customerInfoElement = (StudentInfo)arrayList[i];
customerInfoElement.Show();
}
2.4执行结果