问题描述
我有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>自IEnumerable<删除项目;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!