删除列表 1 中不在列表 2 中的项目
我正在学习编写 lambda 表达式,并且我需要有关如何编写的帮助从列表中删除不在另一个列表中的所有元素。
var list = new List<int> {1, 2, 2, 4, 5};
var list2 = new List<int> { 4, 5 };
// Remove all list items not in List2
// new List Should contain {4,5}
// The lambda expression is the Predicate.
list.RemoveAll(item => item. /*solution expression here*/ );
// Display results.
foreach (int i in list)
{
Console.WriteLine(i);
}
I am learning to write lambda expressions, and I need help on how to remove all elements from a list which are not in another list.
var list = new List<int> {1, 2, 2, 4, 5};
var list2 = new List<int> { 4, 5 };
// Remove all list items not in List2
// new List Should contain {4,5}
// The lambda expression is the Predicate.
list.RemoveAll(item => item. /*solution expression here*/ );
// Display results.
foreach (int i in list)
{
Console.WriteLine(i);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 Contains 通过 RemoveAll 来完成此操作:
或者,如果您只想要交集,请使用 Enumerable.Intersect 会更有效:
不同之处在于,在后一种情况下,您不会获得重复的条目。例如,如果
list2
包含 2,在第一种情况下,您将得到{2,2,4,5}
,在第二种情况下,您将得到 <代码>{2,4,5}。You can do this via RemoveAll using Contains:
Alternatively, if you just want the intersection, using Enumerable.Intersect would be more efficient:
The difference is, in the latter case, you will not get duplicate entries. For example, if
list2
contained 2, in the first case, you'd get{2,2,4,5}
, in the second, you'd get{2,4,5}
.对象的解决方案(可能比 horaces 解决方案更容易):
如果您的列表包含对象而不是标量,那么通过删除对象的一个选定的属性就可以了:
Solution for objects (maybe easier than horaces solution):
If your list contains objects, rather than scalars, it is that simple, by removing by one selected property of the objects:
这个问题已被标记为已回答,但有一个问题。如果您的列表包含一个对象,而不是一个标量,您需要做更多的工作。
我用Remove()和RemoveAt()以及各种各样的方法一遍又一遍地尝试这个,但没有一个能正常工作。我什至无法让 Contains() 正常工作。从来没有匹配过任何东西。我被难住了,直到我怀疑它可能无法正确匹配该项目。
当我意识到这一点时,我重构了 item 类来实现 IEquatable,然后它就开始工作了。
这是我的解决方案:
在我这样做之后,Reed Copsey 的上述RemoveAll() 答案非常适合我。
请参阅:http://msdn.microsoft.com/en-us/library/bhkz42b3 .aspx
This question has been marked as answered, but there is a catch. If your list contains an object, rather than a scalar, you need to do a bit more work.
I tried this over and over with Remove() and RemoveAt() and all sorts of things and none of them worked correctly. I couldn't even get a Contains() to work correctly. Never matched anything. I was stumped until I got the suspicion that maybe it could not match up the item correctly.
When I realized this, I refactored the item class to implement IEquatable, and then it started working.
Here is my solution:
After I did this, the above RemoveAll() answer by Reed Copsey worked perfectly for me.
See: http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx