Search code examples
c#linqlistintersectexcept

Is the order of an except and intersect operation always ignorable?


For me it seems any operation like

var list = new List<int>();
// list.Add some elements...
list.Except(anotherList).Intersect(yetAnotherList)

is this always the same like:

list.Intersect(yetAnotherList).Except(anotherList)

I am not 100% sure.

Thanks for your help.


Solution

  • From a purely set-theoretic perspective the order does not matter here. In both steps you're just removing elements from list. An element is removed from the list if it's either in anotherList or not in yetAnotherList. Whether you switch the operands of the »or« in the previous sentence doesn't make a difference.

    To illustrate, let's construct three lists (sets here, because those are set operations):

    list = { A, B, C, D }
    anotherList = { A, B, E, F }
    yetAnotherList = { A, C, E, G }
    

    Each set here has one element that is in all three sets (A), one element that is in each of the other sets, and one element that is only in that set but not in the others. So we have all possible cases for intersection and set difference covered here.

    list.Except(anotherList) yields { C, D }. Intersecting that with yetAnotherList yields { C }.

    list.Intersect(yetAnotherList) yields { A, C }. Excepting anotherList yields { C } again.