Search code examples
c#stringlistduplicatesremoveall

How to remove strings in list from another list?


I have 2 list which names are listA and listB.

I want to remove strings in listB which are in listA, but I want to do this in this way:

if listA contains: "bar", "bar", "bar", "foo" and listB contains : "bar"

it removes only 1 bar and the result will be: "bar", "bar", "foo"

the code I wrote removes all "bar":

List<string> result = listA.Except(listB).ToList();

Solution

  • You can try to remove it one by one:

    foreach (var word in listB)
        listA.Remove(word);
    

    The Remove method will only remove one element at a time and is not throwing exception (but returning false) when the item is not found: https://msdn.microsoft.com/en-us/library/cd666k3e(v=vs.110).aspx