Remove items from one list in another

PositiveGuy picture PositiveGuy · Apr 30, 2010 · Viewed 195k times · Source

I'm trying to figure out how to traverse a generic list of items that I want to remove from another list of items.

So let's say I have this as a hypothetical example

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();

I want to traverse list1 with a foreach and remove each item in List1 which is also contained in List2.

I'm not quite sure how to go about that as foreach is not index based.

Answer

Mark Byers picture Mark Byers · Apr 30, 2010

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.