例子 1:
public class comper : IComparer
{
int IComparer.Compare(object a, object b)
{
float flotA = 0, flotB = 0;
bool isFloat = float.TryParse(a.ToString(), out flotA) && float.TryParse(b.ToString(), out flotB);
if (!isFloat)
{
return string.Compare(a.ToString(), b.ToString(), false);
}
else
{
return flotA == flotB ? 0 : (flotA>flotB?1:-1);
}
}
}
调用
ArrayList tList = new ArrayList();
IComparer myComperMethod = new comper();
tList.Sort(myComperMethod);
例子 2:
C# code
public class EmployeeInfo
{
public String _Name;
public int _Age;
public EmployeeInfo(String _Name, int _Age)
{
this._Name = _Name;
this._Age = _Age;
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
}
C# code
using System;
using System.Collections;
using System.Reflection;
public class Mycomparator : IComparer
{
public Mycomparator(){ }
int IComparer.Compare(Object o1, Object o2)
{
EmployeeInfo e1 = (EmployeeInfo)o1;
EmployeeInfo e2 = (EmployeeInfo)o2;
if (e1.Age < e2.Age)
return 1;
else if (e1.Age > e2.Age)
return -1;
else
return 0;
}
public static IComparer sortAgeAscending()
{
return (IComparer)new Mycomparator();
}
}
C# code
EmployeeInfo[] arra = new EmployeeInfo[]
{
new EmployeeInfo("张三", 58),
new EmployeeInfo("李四", 26),
new EmployeeInfo("王五", 71),
new EmployeeInfo("赵六", 19)
};
Array.Sort(arra, Mycomparator.sortAgeAscending());
string arr = null;
foreach(EmployeeInfo obj in arra)
{
arr += obj._Name + obj._Age + "<br />";
}
Response.Write(arr);