Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from one List<T> that are found in another

Tags:

I have two lists

 List<T> list1 = new List<T>();
 List<T> list2 = new List<T>();

I want remove all elements from list1, which also exist in list2. Of course I can loop through the first loop looking for each element in list2, but I am looking for elegant solution.

Thanks!

like image 846
Wild Goat Avatar asked Feb 15 '12 14:02

Wild Goat


People also ask

How do you remove an element 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.

What method do you use to remove an item from a list t at a specific index?

RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays.

How do you remove an element from a generic list while iterating over it?

The best way to remove items from a list while iterating over it is to use RemoveAll() .

How do I remove a list of numbers from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.


2 Answers

To change the actual list1 in place, you could use

list1.RemoveAll(item => list2.Contains(item));

You might instead prefer to simply have a query over the lists without modifying either

var result = list1.Except(list2);

LukeH makes a good recommendation in the comments. In the first version, and if list2 is particularly large, it might be worth it to load the list into a HashSet<T> prior to the RemoveAll invocation. If the list is small, don't worry about it. If you are unsure, test both ways and then you will know.

var theSet = new HashSet<YourType>(list2);
list1.RemoveAll(item => theSet.Contains(item));
like image 131
Anthony Pegram Avatar answered Nov 05 '22 20:11

Anthony Pegram


With LINQ:

var result = list1.Except(list2);
like image 28
k.m Avatar answered Nov 05 '22 20:11

k.m