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);
}
You can do this via RemoveAll using Contains:
Alternatively, if you just want the intersection, using Enumerable.Intersect would be more efficient:
The difference is, in the latter case, you will not get duplicate entries. For example, if
list2contained 2, in the first case, you’d get{2,2,4,5}, in the second, you’d get{2,4,5}.