Finding symmetric difference with LINQ

后端 未结 3 1078
心在旅途
心在旅途 2020-12-01 14:13

I have two collections a and b. I would like to compute the set of items in either a or b, but not in both (a logical exc

3条回答
  •  一个人的身影
    2020-12-01 14:42

    Use HashSet directly - it has a SymmetricExceptWith method:

    HashSet data = new HashSet(a);
    data.SymmetricExceptWith(b);
    

    EDIT: If you want to maintain the order, here's an alternative:

    HashSet data = new HashSet(a);
    data.IntersectWith(b);
    foreach (T t in a.Concat(b))
    {
        if (!data.Contains(t))
        {
            yield return t;
        }
    }
    

    This has the following important differences:

    • Both a and b are iterated over twice. In some cases that could be a very bad thing - you could call ToList on each of them to start with to retain a buffer.
    • If there are duplicates in either a or b, they will be yielded multiple times. If you wanted to avoid this you could keep a set of already-yielded values. At this point, it would be equivalent to:

      a.Concat(b).Except(a.Intersect(b))
      

    That's still only two set operations instead of the three in your original code though.

提交回复
热议问题