Remove items from IEnumerable

后端 未结 4 726
醉话见心
醉话见心 2021-01-31 14:25

I have 2 IEnumerable collections.

IEnumerable objectsToExcept 

and

IEnumerable allObjects.
         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 14:57

    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 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.

提交回复
热议问题