刚好知道myCustomCollectionObject 不是List<T>,因此完全重写。
方法一:
在你的类中有一个Sort 方法
List<T> backingStructure; //assuming this is what you have.
public void Sort(IComparer<T> comparer)
{
backingStructure = backingStructure.Where(obj => obj.isValid).ToList();
backingStructure.Sort(comparer);
}
并在内部支持结构上调用Sort。我认为它必须是List<T> 或Array 两者都有Sort。我已将过滤逻辑添加到您的内部
Sort 方法。
方法2:
如果您不希望这样,即您希望您的过滤逻辑在类外部,那么有一种方法可以从IEnumerable<T> 重新填充您的支持结构。喜欢:
List<T> backingStructure; //assuming this is what you have.
//return type chosen to make method name meaningful, up to you to have void
public UndoRedoObservableCollection<T> From(IEnumerable<T> list)
{
backingStructure.Clear();
foreach(var item in list)
//populate and return;
}
这样称呼
myCustomCollectionObject = myCustomCollectionObject.From
(
myCustomCollectionObject.Where(obj => obj.isValid)
.OrderBy(x => x.Key)
);
但您需要一个键来指定排序。
方法 3(最好的):
有一个RemoveInvalid 方法
List<T> backingStructure; //assuming this is what you have.
public void RemoveInvalid()
{
//you can go for non-Linq (for loop) removal approach as well.
backingStructure = backingStructure.Where(obj => obj.isValid).ToList();
}
public void Sort(IComparer<T> comparer)
{
backingStructure.Sort(comparer);
}
叫它:
myCustomCollectionObject.RemoveInvalid();
myCustomCollectionObject.Sort(mycustomerComparer);