对原始集合执行过滤和排序

时间:2013-05-16 09:20:10

标签: c# linq sorting filtering

我遇到了一个场景,我有一个自定义集合类,它继承了ICollection接口的形式,我有一个代码段如下:

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

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

那么,是否有任何方法或解决方法来实施首次过滤然后对原始集合进行排序

2 个答案:

答案 0 :(得分:1)

如果你不能使用Linq的不可变/功能优点,那么你必须走老路:

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

myCustomCollectionObject.Sort(mycustomerComparer);

答案 1 :(得分:0)

刚刚开始学习myCustomCollectionObject不是List<T>,因此完全重写。


方法1:

在您的课程中使用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);
相关问题