根据 ID 成员从列表中删除另一个列表中存在的项目

use*_*167 1 c# linq

我有一个模型:

public class Post
{
    public int PostId { get; set; }
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有两个清单:

List<Post> posts
List<Post> exceptions
Run Code Online (Sandbox Code Playgroud)

我想删除“帖子”中具有与“例外”中项目的 PostId 匹配的所有项目

我努力了:

foreach (var post in posts)
{
    if (exceptions.Where(x => x.PostId == post.PostId) != null)
    {
        posts.RemoveAll(x => x.PostId == post.PostId);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我敢打赌有一种更干净的方法可以做到这一点。

谢谢!

Kar*_*ták 5

只需获取posts您想要保留的并覆盖原始列表即可:

posts = posts.Where(p => !exceptions.Any(e => e.PostId == p.PostId).ToList();
Run Code Online (Sandbox Code Playgroud)