从与其它标准列表中删除列表项 [英] Remove items of list from another lists with criteria
问题描述
我有作家的名单。
public class Writers{
long WriterID { get;set; }
}
另外我有类型的文章两份清单。
Also I have two lists of type Article.
public class Article{
long ArticleID { get; set; }
long WriterID { get; set; }
//and others
}
因此code我已经是:
so the code i have is:
List<Article> ArticleList = GetList(1);
List<Article> AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();
我想从 ArticleList
, AnotherArticleList
删除这些记录,其中 WriterID
从 listWriters
WriterID
。如何做到这一点的LINQ?
I want to remove those records from ArticleList
, AnotherArticleList
where WriterID
matches from listWriters
WriterID
. How to do this in LINQ?
推荐答案
如果你确实有一个名单,其中,T&GT;
,我建议你使用<一个href="http://msdn.microsoft.com/en-us/library/wdka673a.aspx"><$c$c>List<T>.RemoveAll$c$c>,构建了一套作家的ID之后:
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));
如果您的不的想使用LINQ,你可以使用:
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();
请注意,这个改变的变量的,但不修改现有的列表 - 所以,如果有任何其他引用相同的列表,他们将不会看到任何变化。 (而 removeall过
修改现有列表。)
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.)
这篇关于从与其它标准列表中删除列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!