HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Build List from unshared items from two other Lists

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
unsharedothertwoitemslistslistfrombuild

Problem

Ultimately, my goal is to take two lists and then generate a third consisting of items that the first two lists do NOT share. I am able to get the results I want using two foreach loops, but I am hoping to learn about some magical List tool that will do it more cleanly.

public List removeMatchingItems(List List1, List List2)
{
    List desiredList = new List();

    foreach (string value in List1)
    {
        if (!List2.Contains(value))
        { desiredList.Add(value); }
    }
    foreach (string value in List2)
    {
        if (!List1.Contains(value))
        { desiredList.Add(value); }
    }
    return desiredList;
}

Solution

The operation is called the symmetric difference of List1 and List2. You can write

return list1.Except(list2).Union(list2.Except(list1)).ToList();

Code Snippets

return list1.Except(list2).Union(list2.Except(list1)).ToList<string>();

Context

StackExchange Code Review Q#78681, answer score: 7

Revisions (0)

No revisions yet.