Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from list 1 not in list 2

Tags:

c#

lambda

I am learning to write lambda expressions, and I need help on how to remove all elements from a list which are not in another list.

var list = new List<int> {1, 2, 2, 4, 5}; var list2 = new List<int> { 4, 5 };  // Remove all list items not in List2 // new List Should contain {4,5}     // The lambda expression is the Predicate. list.RemoveAll(item => item. /*solution expression here*/ );  // Display results. foreach (int i in list) {     Console.WriteLine(i); } 
like image 872
TheMar Avatar asked Nov 01 '10 01:11

TheMar


People also ask

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

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 delete all items from one list to another in Python?

Using list.list. clear() is the recommended solution in Python 3 to remove all items from the list.

How do you remove the first element from a list in Python?

The remove() function allows you to remove the first instance of a specified value from the list. This can be used to remove the list's top item. Pick the first member from the list and feed it to the remove() function.


2 Answers

You can do this via RemoveAll using Contains:

list.RemoveAll( item => !list2.Contains(item)); 

Alternatively, if you just want the intersection, using Enumerable.Intersect would be more efficient:

list = list.Intersect(list2).ToList(); 

The difference is, in the latter case, you will not get duplicate entries. For example, if list2 contained 2, in the first case, you'd get {2,2,4,5}, in the second, you'd get {2,4,5}.

like image 196
Reed Copsey Avatar answered Sep 17 '22 17:09

Reed Copsey


Solution for objects (maybe easier than horaces solution):

If your list contains objects, rather than scalars, it is that simple, by removing by one selected property of the objects:

    var a = allActivePatientContracts.RemoveAll(x => !allPatients.Select(y => y.Id).Contains(x.PatientId)); 
like image 30
M.Buschmann Avatar answered Sep 18 '22 17:09

M.Buschmann