Remove items of list from another lists with criteria
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.)
articlesList.RemoveAll(a => listWriters.Exists(w => w.WriterID == a.WriterID));
anotherArticlesList.RemoveAll(a => listWriters.Exists(w => w.WriterID == a.WriterID));
You can use Except:
List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
List<car> result = list2.Except(list1).ToList();
I do not really see what is the difficulty you are facing...
Why don't you just filter/remove data from you lists using a simple for loop ? (Note that a foreach Loop will definitely NOT work if you iterate while editing/changing the iterated object)
for (int i = ArticleList.Count -1; i >= 0; i--)
{
for (int j = 0; j < listWriters.Count; j++)
{
if (ArticleList[i].WriterId == listWriters[j].WriterID )
ArticleList.RemoveAt(i);
}
}
The Backward iteration trick solves the "delete items while iterating" paradigm.