7
\$\begingroup\$

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<string> removeMatchingItems(List<string> List1, List<string> List2)
{
    List<string> desiredList = new List<string>();

    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;
}
\$\endgroup\$
0

2 Answers 2

7
\$\begingroup\$

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

return list1.Except(list2).Union(list2.Except(list1)).ToList<string>();
\$\endgroup\$
2
  • 3
    \$\begingroup\$ Reviewing the reviewer: I don't think you need to specify string in the ToList call. Not 100% on that without being in front of my IDE. \$\endgroup\$
    – RubberDuck
    Commented Jan 26, 2015 at 22:34
  • \$\begingroup\$ You are correct, the string part is unnecessary in the ToList method. To be honest I didn't even think to try it without. \$\endgroup\$ Commented Jan 27, 2015 at 13:32
2
\$\begingroup\$

First of all I am going to complain about your if blocks and the way that you brace them. I don't like it and I don't think many other people would enjoy it either.

if (condition)
{
    //Do Work
}

This might be more of a personal preference, but I would rather call this method GetMisMatchedItems. Something that I did here without even realizing it is that I used PascalCasing for the Method name instead of camelCasing, this is a C# standard.

With these changes I think it looks much cleaner looking.

public List<string> GetMisMatchedItems(List<string> List1, List<string> List2)
{
    List<string> desiredList = new List<string>();

    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;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.