写了一个对象集合排序的类
写了一个对象集合排序的类
废话不多说,首先是定义一个对象实体类
class Entity
{
public Entity()
{}
private int id;
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private double price;
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
}
{
public Entity()
{}
private int id;
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private double price;
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
}
然后写一个对象比较的类,实现IComparer<T>接口。
internal class ListComparer<TBaseBusinessObject> : IComparer<TBaseBusinessObject>
{
private string propertyName;
public ListComparer(string PropertyName)
{
propertyName = PropertyName;
}
IComparer Members
}
{
private string propertyName;
public ListComparer(string PropertyName)
{
propertyName = PropertyName;
}
IComparer
}
然后是写了一个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();
}
}
{
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);
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);
完了~~~