开发者

Generic List RemoveAll and lambda expressions

I'm clearly missing something here... I have a generic list of objects and I'm trying to use a lambda expression to remove items. When I use the code posted below I get the following exception.

System.InvalidOperationException: Sequence contains no matching element

public class MyObject {
    public Guid ID1 {get;set;}
    public int ID2 {g开发者_Python百科et;set;}
}

public class MyContainer{
    List<MyObject> myList = new List<MyObject>();

    public MyObject Get(Guid id1) {
        return myList.Single(mo => mo.ID1 == id1);
    }

    public void AddItem(MyObject item) {
        myList.Add(item);
    }

    public int RemoveItems(MyObject item) {
        return myList.RemoveAll(mo => mo.ID1 == item.ID1 || mo.ID2 == item.ID2);
    }
}

Am I making a mistake using a lambda?

[EDIT] Well a flop for the first question. I misread the stack trace, after removing the item in my unit test I tried to call the Get() method and in my "why is it already dark out" rage jumped the gun on posting a question without appropriate analysis. Sorry.


"Sequence contains no matching element" is more a First(predicate) or Single(predicate) thing... I wouldn't expect to see this from RemoveAll. Are you sure it is in the code posted?

The line:

new MyContainer().RemoveItems(new MyObject { ID1 = Guid.Empty, ID2 = 2 });

Runs without any error. I'm wondering if you are calling something like:

col.RemoveItems(someQuery.Single(predicate));

and it happens that someQuery is empty.


It appears you are only removing the one MyObject being passed into the method. If this is the case, you can modify your code to say myList.Remove as opposed to myList.RemoveAll


I'm assuming you're trying to cover the case where multiple items with the same ID appear in the list (otherwise just use Remove). If so, try storing the lambda like:

Expression<Func<MyObject, bool>> pred = (mo) => mo.ID1 == item.ID1 || mo.ID2 == item.ID2

and only call myList.RemoveAll(pred) if myList.Any(pred) is true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜