IComparable这个接口我也试过了,同样不行哟
程序代码: this.dgvRoom.DataSource = new SortList<RoomType>(roomTypeManager.GetAllRoomType());
private class SortList<T> : BindingList<T>
{
private bool isSortedCore = true;
private ListSortDirection sortDirectionCore = ListSortDirection.Ascending;
private PropertyDescriptor sortPropertyCore = null;
private string defaultSortItem;
public SortList() : base() { }
public SortList(IList<T> list) : base(list) { }
//重写父类方法:是否支持排序
protected override bool SupportsSortingCore
{
get
{
return true;
}
}
//是否支持搜索
protected override bool SupportsSearchingCore
{
get
{
return true;
}
}
//是否已经排序
protected override bool IsSortedCore
{
get
{
return this.isSortedCore;
}
}
//排序的方向
protected override ListSortDirection SortDirectionCore
{
get
{
return this.sortDirectionCore;
}
}
//获取用于对列表排序的属性说明符
protected override PropertyDescriptor SortPropertyCore
{
get
{
return this.sortPropertyCore;
}
}
protected override int FindCore(PropertyDescriptor prop, object key)
{
for (int i = 0; i < this.Count; i++)
{
if (Equals(prop.GetValue(this[i]),key)) return i;
}
return 1;
}
//对项进行排序
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
this.isSortedCore = true;
this.sortDirectionCore = direction;
this.sortPropertyCore = prop;
Sort();
}
//移除
protected override void RemoveSortCore()
{
if (this.isSortedCore)
{
this.isSortedCore = false;
this.sortPropertyCore = null;
this.sortDirectionCore = ListSortDirection.Descending;
Sort();
}
}
//默认排序属性
private string DefaultSortItem
{
get { return this.defaultSortItem; }
set { if (defaultSortItem != value) defaultSortItem = value; Sort(); }
}
private void Sort()
{
List<T> list = (this.Items as List<T>);
list.Sort(CompareCore);
ResetBindings();
}
//比较
private int CompareCore(T o1, T o2)
{
int ret = 0;
if (SortPropertyCore != null)
{
ret = CompareValue(SortPropertyCore.GetValue(o1), SortPropertyCore.GetValue(o2), SortPropertyCore.PropertyType);
}
if (ret == 0 && DefaultSortItem != null)
{
PropertyInfo property = typeof(T).GetProperty(DefaultSortItem, BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.IgnoreCase, null, null, new Type[0], null);
if (property != null)
{
ret = CompareValue(property.GetValue(o1, null), property.GetValue(o2, null), property.PropertyType);
}
}
if(SortDirectionCore==ListSortDirection.Descending) ret=-ret;
return ret;
}
private static int CompareValue(object o1,object o2,Type type)
{
if (o1 == null) return o2 == null ? 0 : -1;
else if (o2 == null) return 1;
else if (type.IsPrimitive || type.IsEnum) return Convert.ToDouble(o1).CompareTo(Convert.ToDouble(o2));
else if (type == typeof(DateTime)) return Convert.ToDateTime(o1).CompareTo(Convert.ToDateTime(o2));
else if (type == typeof(Int32)) return Convert.ToInt32(o1).CompareTo(Convert.ToInt32(o2));
else return (o1.ToString().Trim(), o2.ToString().Trim());
}
}
