[英]Remove items of list from another lists with criteria
i have a list of writers. 我有一份作家名单。
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
}
so the code i have is: 所以我的代码是:
List<Article> ArticleList = GetList(1);
List<Article> AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();
I want to remove those records from ArticleList
, AnotherArticleList
where WriterID
matches from listWriters
WriterID
. 我想从ArticleList
, AnotherArticleList
中删除那些记录,其中WriterID
与listWriters
WriterID
匹配。 How to do this in LINQ? 如何在LINQ中执行此操作?
If you've actually got a List<T>
, I suggest you use List<T>.RemoveAll
, after constructing a set of writer IDs: 如果你实际上有一个List<T>
,我建议你在构造一组List<T>.RemoveAll
ID之后使用List<T>.RemoveAll
:
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: 如果您确实想使用LINQ,可以使用:
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.) (而RemoveAll
修改现有列表。)
articlesList.RemoveAll(a => listWriters.Exists(w => w.WriterID == a.WriterID));
anotherArticlesList.RemoveAll(a => listWriters.Exists(w => w.WriterID == a.WriterID));
Just a design tip, your class should be called Writer
(singular form), not Writers
(plural). 只是一个设计提示,你的课应该被称为Writer
(单数形式),而不是Writers
(复数)。 Each item in your list represents a single writer, correct? 列表中的每个项目代表一个作者,对吗?
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 ? 为什么不使用简单的for循环过滤/删除列表中的数据? (Note that a foreach Loop will definitely NOT work if you iterate while editing/changing the iterated object) (注意,如果在编辑/更改迭代对象时进行迭代,则foreach循环肯定不起作用)
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. 向后迭代技巧解决了“迭代时删除项目”范例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.