c# – 如何对原位进行排序?
发布时间:2020-12-15 18:07:41 所属栏目:百科 来源:网络整理
导读:我有一个通用的集合: public Items : CollectionObject{ protected override void InsertItem(int index,Object item) { base.InsertItem(index,item); ... } protected override void RemoveItem(int index) { base.RemoveItem(index); ... } protected ov
|
我有一个通用的集合:
public Items : Collection<Object>
{
protected override void InsertItem(int index,Object item)
{
base.InsertItem(index,item);
...
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
...
}
protected override void SetItem(int index,Object item)
{
base.SetItem(index,item);
...
}
protected override void ClearItems()
{
base.ClearItems();
...
}
现在我需要一种方式来对原来的这个集合进行排序. 奖金喋喋不休 我尝试将我的类转换为使用List< T>而不是集合< T> (因为Collection< T>不支持订单的概念).然后允许调用Sort方法: this.Items.Sort(SortCompareCallback);
protected virtual int SortCompareCallback(Object x,Object y)
{
return OnCompareItems(new SortCompareEventArgs(x,y,this.sortColumnIndex,direction));
}
但是当列表被修改时,我会丢失虚拟方法. 我想过使用Linq,但问题是: >我不知道如何从Linq表达式调用回调 如何排序一般的Collection< T>? 解决方法
如果您不需要在排序期间调用虚拟覆盖,则应该能够执行以下操作:
class SortableCollection<T> : Collection<T>
{
private readonly List<T> _list;
public SortableCollection() : this(new List<T>()) {}
public SortableCollection(List<T> list) : base(list)
{
_list = list;
}
public void Sort() { _list.Sort(); }
}
或这个: class SortableCollection<T> : Collection<T>
{
public SortableCollection() : this(new List<T>()) {}
public SortableCollection(List<T> list) : base(list) {}
public void Sort() { ((List<T>)Items).Sort(); }
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
