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 that will not work. The counter after the execution of the methods indicates that the elements have not been deleted.

+43
c # linq ienumerable
Jul 06 '10 at 12:01
source share
5 answers

I don’t see how the first version will be compiled, and the second version will not do anything if you do not use the result. It does not delete anything from the existing collection - indeed, there can be no internal memory in it. It simply returns a sequence that, after repeating, will return the corresponding values.

If you use a result like

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

then this should be good if you redefined GetHashCode and Equals , or if you are happy to use reference equality. Are you trying to remove logically equal values ​​or make the same links in both sequences? You redefined GetHashCode and Equals , and if so, are you sure these implementations work?

In principle, this should be good - I suggest you try creating a short but complete program that demonstrates the problem; I suspect that in doing so you will know what is wrong.

+58
Jul 06 2018-10-06T00:
source share

IEnumerable<T> does not have a Remove method, since it is not intended to be modified.

The Except method does not modify the original collection: it returns a new collection that does not contain excluded elements:

 var notExcluded = allObjects.Except(objectsToExcept); 

See Except on MSDN .

+28
Jul 6 2018-10-06T00:
source share

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

 var result = allObject.Except(objectsToexcept); 
+16
Jul 06 2018-10-06T00:
source share

While the other answers are correct, I must add that the result of calling Except() can be returned back to the original variable. I.e

 allObjects = allObjects.Except(objectsToExcept); 

Also keep in mind that Except() will create the specified difference between the two collections, so if there are duplicate variables that need to be deleted, they will all be deleted.

+3
Sep 30 '12 at 23:01
source share
 others.Where(contract => !objectsToExcept.Any()).ToList(); 
0
May 02 '14 at 13:49
source share



All Articles