Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to remove certain elements from a IList<T> based on a IList<int> [duplicate]

Tags:

c#

linq

ilist

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.

like image 877
passionatedeveloper Avatar asked May 17 '13 09:05

passionatedeveloper


1 Answers

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.

like image 122
Daniel Hilgarth Avatar answered Oct 21 '22 12:10

Daniel Hilgarth