Remove items from one list in another
Solution 1:
You can use Except:
List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
List<car> result = list2.Except(list1).ToList();
You probably don't even need those temporary variables:
List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();
Note that Except
does not modify either list - it creates a new list with the result.
Solution 2:
You don't need an index, as the List<T>
class allows you to remove items by value rather than index by using the Remove
function.
foreach(car item in list1) list2.Remove(item);
Solution 3:
I would recommend using the LINQ extension methods. You can easily do it with one line of code like so:
list2 = list2.Except(list1).ToList();
This is assuming of course the objects in list1 that you are removing from list2 are the same instance.