T>自IEnumerable&LT删除项目; [英] Remove items from IEnumerable<T>

查看:109
本文介绍了T>自IEnumerable&LT删除项目;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个集合的IEnumerable

I have 2 IEnumerable collections.

IEnumerable<MyClass> objectsToExcept 

IEnumerable<MyClass> allObjects.



objectsToExcept 可能包含来自<$ C对象$ C> allObjects 。

我需要从 allObjects 对象<$删除C $ C> objectsToExcept 。例如:

foreach (var myClass in objectsToExcept)
{
allObjects.Remove(myClass);
}

allObject.Except(objectsToExcept)

但它不工作。该方法已经执行后的数表明,没有任何项目已被删除。

But it doesn't work. The count after the methods have execute indicate that no items have been removed.

推荐答案

我没有看到的第一个版本会怎样编译,除非你使用结果的第二个版本将无法做任何事情。它不会从现有集合中删除任何东西 - 事实上,也有可能甚至没有的可以的内存中的集合支持它。它只是返回一个序列,当遍历,将返回相应的值。

I don't see how the first version would compile, and the second version won't do anything unless you use the result. It doesn't remove anything from the existing collection - indeed, there may not even be an in-memory collection backing it. It just returns a sequence which, when iterated over, will return the appropriate values.

如果您的的使用结果,如:

If you are using the result, e.g.

IEnumerable<MyClass> others = allObjects.Except(objectsToExcept);
foreach (MyClass x in others)
{
    ...
}

那么它应该罚款的如果的你已经覆盖的GetHashCode 等于的,如果你乐于使用引用相等。你们是不是要删除逻辑上相等的值,或做同样的引用的发生在这两个序列?你有没有覆盖的GetHashCode 等于,如果是这样,你确定这些实现的工作?

then it should be fine if you've overridden GetHashCode and Equals or if you're happy to use reference equality. Are you trying to remove logically-equal values, or do the same references occur in both sequences? Have you overridden GetHashCode and Equals, and if so, are you sure those implementations work?

基本上,它应该罚款 - 我建议你尝试创建一个简短而完整的程序,演示该问题;我怀疑,而这样做,你会发现什么是错的。

Basically it should be fine - I suggest you try to create a short but complete program that demonstrates the problem; I suspect that while doing so, you'll find out what's wrong.

这篇关于T&GT;自IEnumerable&LT删除项目;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆