Get the symmetric difference from generic lists

Viewed 6161

I have 2 separate List and I need to compare the two and get everything but the intersection of the two lists. How can I do this (C#)?

7 Answers

Here is a generic Extension method. Rosetta Code uses Concat, and Djeefther Souza says it's more efficient.

public static class LINQSetExtensions
{
    // Made aware of the name for this from Swift
    // https://stackoverflow.com/questions/1683147/get-the-symmetric-difference-from-generic-lists
    // Generic implementation adapted from https://www.rosettacode.org/wiki/Symmetric_difference
    public static IEnumerable<T> SymmetricDifference<T>(this IEnumerable<T> first, IEnumerable<T> second)
    {
        // I've used Union in the past, but I suppose Concat works. 
        // No idea if they perform differently. 
        return first.Except(second).Concat(second.Except(first));
    }
}

I haven't actually benchmarked it. I think it would depend on how Union vs. Concat are implemented. In my dreamworld, .NET uses a different algorithm depending on data type or set size, though for IEnumerable it can't determine set size in advance.

Also, you can pretty much ignore my answer - Jon Skeet says that the HashSet method "Excellent - that looks like the best way of doing it to me."

Related