Remove items of list from another lists with criteria
Solution 1:
If you've actually got a List<T>
, I suggest you use List<T>.RemoveAll
, after constructing a set of writer IDs:
HashSet<long> writerIds = new HashSet<long>(listWriters.Select(x => x.WriterID));
articleList.RemoveAll(x => writerIds.Contains(x.WriterId));
anotherArticleList.RemoveAll(x => writerIds.Contains(x.WriterId));
If you do want to use LINQ, you could use:
articleList = articleList.Where(x => !writerIds.Contains(x.WriterId))
.ToList();
anotherArticleList = anotherArticleList
.Where(x => !writerIds.Contains(x.WriterId))
.ToList();
Note that this changes the variable but doesn't modify the existing list - so if there are any other references to the same list, they won't see any changes. (Whereas RemoveAll
modifies the existing list.)
Solution 2:
articlesList.RemoveAll(a => listWriters.Exists(w => w.WriterID == a.WriterID));
anotherArticlesList.RemoveAll(a => listWriters.Exists(w => w.WriterID == a.WriterID));