Search code examples
c#linqcompareienumerable

Compare contents of two IEnumerables


Is there a built in LINQ method thing I can use to find out if two sequences contains the same items, not taking the order into account?

For example:

{1, 2, 3} == {2, 1, 3}
{1, 2, 3} != {2, 1, 3, 4}
{1, 2, 3} != {1, 2, 4}

You have the SequenceEquals, but then I would have to Order both sequences first, wouldn't I?


Solution

  • There are quite a few ways. Assume A and B is IEnumerable.

    !A.Except(B).Any() && !B.Except(A).Any()
    A.Count() == B.Count() && A.Intersect(B).Count() == B.Count()
    etc