1

我陷入了这样一个场景,即我有一个自定义集合类,它继承了 ICollection 接口的形式,并且我有一个如下代码段:

myCustomCollectionObject.Where(obj=>obj.isValid).ToList().Sort(mycustomerComparer);

上面的代码过滤原始集合,然后对集合进行排序,在这种场景中,排序将在不同的集合而不是原始集合上执行。

那么,有什么方法或解决方法可以实现第一次过滤然后对原始集合进行排序

4

2 回答 2

1

如果您不能使用 Linq 的不可变/功能优势,那么您必须使用老派:

//Remove unwanted items
for (int i = myCustomCollectionObject.Length; i >= 0 ; i--)
{
    if(!myCustomCollectionObject[i].IsValid)
        myCustomCollectionObject.Remove(myCustomCollectionObject[i]);
}

myCustomCollectionObject.Sort(mycustomerComparer);
于 2013-05-16T09:33:01.897 回答
0

只是碰巧学到了myCustomCollectionObjectis not 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方法中。

方法二:

如果您不希望这样,即您希望您的过滤逻辑在类外部,那么有一种方法可以从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);
于 2013-05-16T12:48:07.723 回答