How to use LINQ to remove certain elements from a IList based on another IList. I need to remove records from list1 where ID is present in list2. Below is the code sample,
class DTO
{
Prop int ID,
Prop string Name
}
IList<DTO> list1;
IList<int> list2;
foreach(var i in list2)
{
var matchingRecord = list1.Where(x.ID == i).First();
list1.Remove(matchingRecord);
}
This is how I am doing it, is there a better way to do the same.
I would use this approach:
var itemsToRemove = list1.Where(x => list2.Contains(x.ID)).ToList();
foreach(var itemToRemove in itemsToRemove)
list1.Remove(itemToRemove);
This approach removes the items in place. It is best used for cases where there are many items in list1 and few in list2.
If the amount of items in list1 and list2 is similar, the approach from Cuong Le is a good alternative.
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