views:

161

answers:

3

i have 2 IEnumerable collections.

IENumerable<MyClass> objectsToExcept 

and

IENumerable<MyClass> allObjects.

objectsToExcept may contain objects from allObjects.

I need to remove from allObjects objects in objectsToExcept. For ex:

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

OR

allObject.Except(objectsToExcept)

But it doesn't work. The count after deleting is same, without any exceptions

+13  A: 

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)
{
    ...
}

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.

Jon Skeet
Beat me to it! :)
Matt Ellen
+4  A: 

Remove and Except do not modify the original IEnumerable. They return a new one. try

var result = allObject.Except(objectsToexcept);
Mike Two
+8  A: 

There is no Remove method on IEnumerable<T>, because it is not meant to be modifiable.

The Except method doesn't modify the original collection : it returns a new collection that doesn't contain the excluded items :

var notExcluded = allObjects.Except(objectsToExcept);
Thomas Levesque
`Remove` exists as an extension method in the Linq to XML space, but doesn't do what the OP is trying to do. Oddly enough you see it on the documentation page for the members of `IEnumerable<T>` but it has a restriction `where T : XNode`. Technically `Except` isn't on `IEnumerable<T>` either, but that is being absolutely too picky.
Mike Two
@Mike Two, indeed, I never noticed that... it looks like a bug in the documentation
Thomas Levesque