您的位置:首页 > 其它

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"));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: