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); }
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.
Using list.list. clear() is the recommended solution in Python 3 to remove all items from the list.
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.
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}
.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With