List 泛型列表通用排序
2008-12-23 14:01
330 查看
List集合类里面有个Sort方法可以自定义排序。如果我们有个List<T>集合类,我要按某个属性升序或降序排序怎么做呢,我的做法是:List.Sort (Generic Comparison)
1:protected Comparison<T> SortByName<T>(string name)
{
Comparison<T> c = delegate(T x, T y)
{
if (x == null)
{
if (y == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (y == null)
{
return 1;
}
else
{
PropertyInfo px = x.GetType().GetProperty(name);
if (px == null) return 1;
object vx = px.GetValue(x, null);
PropertyInfo py = y.GetType().GetProperty(name);
object vy = py.GetValue(y, null);
if (vx == null)
{
if (vy == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (vy == null)
{
return 1;
}
else
{
if (vx is string)
{
return ((string)vx).CompareTo((string)vy);
}
else if (vx is DateTime)
{
return ((DateTime)vx).CompareTo((DateTime)vy);
}
else if (vx is int)
{
return ((int)vx).CompareTo((int)vy);
}
else if (vx is decimal)
{
return ((decimal)vx).CompareTo((decimal)vy);
}
else if (vx is double)
{
return ((double)vx).CompareTo((double)vy);
}
return 1;
}
}
}
}
};
return c;
}
调用排序:List.Sort(SortByName<T>("name"));
1:protected Comparison<T> SortByName<T>(string name)
{
Comparison<T> c = delegate(T x, T y)
{
if (x == null)
{
if (y == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (y == null)
{
return 1;
}
else
{
PropertyInfo px = x.GetType().GetProperty(name);
if (px == null) return 1;
object vx = px.GetValue(x, null);
PropertyInfo py = y.GetType().GetProperty(name);
object vy = py.GetValue(y, null);
if (vx == null)
{
if (vy == null)
{
return 0;
}
else
{
return -1;
}
}
else
{
if (vy == null)
{
return 1;
}
else
{
if (vx is string)
{
return ((string)vx).CompareTo((string)vy);
}
else if (vx is DateTime)
{
return ((DateTime)vx).CompareTo((DateTime)vy);
}
else if (vx is int)
{
return ((int)vx).CompareTo((int)vy);
}
else if (vx is decimal)
{
return ((decimal)vx).CompareTo((decimal)vy);
}
else if (vx is double)
{
return ((double)vx).CompareTo((double)vy);
}
return 1;
}
}
}
}
};
return c;
}
调用排序:List.Sort(SortByName<T>("name"));
相关文章推荐
- 泛型列表(List)的搜索和排序
- Gridview 绑定泛型List<T> 排序方法
- List对象排序的通用方法
- java中List对象列表去重或取出以及排序
- 3個對泛型 List 排序的方法
- android list列表排序
- 关于对List的通用排序实现
- List<T>列表通用过滤
- 按首字母分类并排序显示的列表(二)--给BaseExpandableListAdapter提供数据的HashList
- 包含对象为Integer的List列表转为Integer数组并排序的简单方法
- List对象排序通用方法
- List Control(列表)排序,无需回调函数
- List<T>泛型数组API自带的Sort() 排序方法根据自定义排序实现
- java中List对象排序通用方法
- python备忘六:list 列表之序列通用操作
- 通用的泛型Icomparer生成类,对类进行排序,最大支持4个字段同时比较
- 列表List和泛型
- ASP.NET通用权限管理系统(FrameWork) 之用户在线列表 泛型缓存 [原创]
- List排序通用方法
- 利用泛型实现通用的list和array转换