其实重点在于实现 IComparer 接口,实现按照自已的来排序
class Entity
{
public Entity()
{}
private int id;
public int Id
get
return id;
}
set
id = value;
}
private string name;
public string Name
return name;
name = value;
private double price;
public double Price
return price;
price = value;
}
然后写一个对象比较的类,实现IComparer<T>接口。
internal class ListComparer<TBaseBusinessObject> : IComparer<TBaseBusinessObject>
private string propertyName;
public ListComparer(string PropertyName)
propertyName = PropertyName;
IComparer Members#region IComparer<TBaseBusinessObject> Members
public int Compare(TBaseBusinessObject x, TBaseBusinessObject y)
PropertyInfo property = typeof(TBaseBusinessObject).GetProperty(propertyName);
if (property.PropertyType == Type.GetType("System.Int16"))
int xNumber = 0;
int yNumber = 0;
if (property.GetValue(x, null) != null)
xNumber = Convert.ToInt16(property.GetValue(x, null).ToString());
}
if (property.GetValue(y, null) != null)
yNumber = Convert.ToInt16(property.GetValue(y, null).ToString());
return xNumber.CompareTo(yNumber);
if (property.PropertyType == Type.GetType("System.Int32"))
xNumber = Convert.ToInt32(property.GetValue(x, null).ToString());
yNumber = Convert.ToInt32(property.GetValue(y, null).ToString());
if (property.PropertyType == Type.GetType("System.Double"))
double xNumber = 0;
double yNumber = 0;
xNumber = Convert.ToDouble(property.GetValue(x, null).ToString());
yNumber = Convert.ToDouble(property.GetValue(y, null).ToString());
if (property.PropertyType == Type.GetType("System.DateTime"))
DateTime xTime = DateTime.Now;
DateTime yTime = DateTime.Now;
xTime = Convert.ToDateTime(property.GetValue(x, null).ToString());
yTime = Convert.ToDateTime(property.GetValue(y, null).ToString());
return xTime.CompareTo(yTime);
if ((property.PropertyType == Type.GetType("System.String")) || (property.PropertyType == Type.GetType("System.Boolean")))
string xText = string.Empty;
string yText = string.Empty;
xText = property.GetValue(x, null).ToString();
yText = property.GetValue(y, null).ToString();
return xText.CompareTo(yText);
return 0;
#endregion
然后是写了一个List继承List<T>类的集合,
public class BaseBusinessObjectList<TBaseBusinessObject> : List<TBaseBusinessObject>
public void Sort(string sortfield, bool isAscending)
//这里实例化了刚才写的IComparer类。
ListComparer<TBaseBusinessObject> listComparer = new ListComparer<TBaseBusinessObject>(sortfield);
base.Sort(listComparer);
if (!isAscending) base.Reverse();
于是就写完了,用的时候
BaseBusinessObjectList<Entity> list = new BaseBusinessObjectList<Entity>();
Entity obj = new Entity();
obj.Id = 1;
obj.Name = "test";
obj.Price = 3.23;
list.Add(obj);
//按照Name字段向上排序。
list.Sort("Name",true);
//按照Price字段向上排序。
list.Sort("Price",true);
//按照Id字段向下排序。
list.Sort("Id",false);
完了~~~