Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from one list in another

Tags:

c#

.net

list

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.

like image 816
PositiveGuy Avatar asked Apr 30 '10 15:04

PositiveGuy


People also ask

How do you remove items from a list from one list to another in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do you remove an element from one list to another list?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.

How do I remove an item from a list in Python?

Items of the list can be deleted using del statement by specifying the index of item (element) to be deleted. We can remove an item from the list by passing the value of the item to be deleted as the parameter to remove() function. pop() is also a method of list.


2 Answers

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.

like image 152
Mark Byers Avatar answered Oct 26 '22 14:10

Mark Byers


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); 
like image 44
Adam Robinson Avatar answered Oct 26 '22 15:10

Adam Robinson