How can be the following code converted to linq or predicate expression:
List list1 = new List {1,2,3,4,5};
List list2= new
You could do something like this:
list1.ForEach( x => { list2.Remove(x); } );
You can use Except():
list2 = list2.Except(list1)
.ToList();
This also will perform better than your original code, since your code is O(n2) doing a loop over all items in the first collection, then trying to find the first match in the second collection. (Although admittedly the performance difference will not matter much if your collections are this small, but it will matter significantly for large collections).
Except()
will create a HashSet<int>
of list1
internally and then just traverse the list2
collection. Only items that are not contained in the HashSet
end up in the result enumeration - since the HashSet
lookup is O(1) on average this will result in O(n) effort all in all.
For an educational refresher see Jon Skeets EduLinq series, here the chapter for Except.
list2.RemoveAll(m=>list1.Contains(m));