通用列表RemoveAll和lambda表达式
我显然在这里遗漏了一些东西...我有一个通用的对象列表,并且我正在尝试使用 lambda 表达式来删除项目。当我使用下面发布的代码时,出现以下异常。
System.InvalidOperationException:序列不包含匹配元素
public class MyObject {
public Guid ID1 {get;set;}
public int ID2 {get;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);
}
}
我使用 lambda 时犯了错误吗?
[编辑] 第一个问题就失败了。我误读了堆栈跟踪,在删除单元测试中的项目后,我尝试调用 Get() 方法,并且在我的“为什么天已经黑了”的愤怒中,在没有适当分析的情况下就发布了问题。对不起。
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 {get;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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“序列不包含匹配元素”
更像是First(predicate)
或Single(predicate)
事物......我不希望请参阅RemoveAll
。您确定它在发布的代码中吗?该行:
运行没有任何错误。我想知道您是否正在调用类似的内容:
并且
someQuery
恰好为空。"Sequence contains no matching element"
is more aFirst(predicate)
orSingle(predicate)
thing... I wouldn't expect to see this fromRemoveAll
. Are you sure it is in the code posted?The line:
Runs without any error. I'm wondering if you are calling something like:
and it happens that
someQuery
is empty.看来您只是删除了传递到该方法中的一个 MyObject。如果是这种情况,您可以修改代码以显示 myList.Remove 而不是 myList.RemoveAll
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
我假设您试图涵盖列表中出现多个具有相同 ID 的项目的情况(否则只需使用“删除”)。如果是这样,请尝试像这样存储 lambda:
并且仅在 myList.Any(pred) 为 true 时才调用 myList.RemoveAll(pred)。
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:
and only call myList.RemoveAll(pred) if myList.Any(pred) is true.