简体   繁体   中英

Remove items from IEnumerable<T>

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 example:

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

Or

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, eg

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.

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);

See Except on MSDN .

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

var result = allObject.Except(objectsToexcept);

While the other answers are correct, I have to add that the result of the Except() call can be assigned back to the original variable. That is,

allObjects = allObjects.Except(objectsToExcept);

Also keep in mind that Except() will produce the set difference of the two collections, so if there are duplicates of the variables to be removed, they will all be removed.

others.Where(contract => !objectsToExcept.Any()).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM