簡體   English   中英

從列表中刪除基於ID成員的另一個列表中存在的項目

[英]removing items from list that exist in another list based on an ID member

我有一個模型:

public class Post
{
    public int PostId { get; set; }
    public string Description { get; set; }
}

我有兩個清單:

List<Post> posts
List<Post> exceptions

我要刪除“帖子”中具有與“例外”中的項目相匹配的PostId的所有項目

我努力了:

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

但是我敢打賭,這里有一種更清潔的方法。

謝謝!

只需獲取要保留的posts並覆蓋原始列表即可:

posts = posts.Where(p => !exceptions.Any(e => e.PostId == p.PostId).ToList();

第一點:對帖子進行foreach時,您無法刪除任何帖子。

您應該使用for循環。

第二點:在循環之前,在每個postid和包含thid id的對象發布之間使用映射。 這樣您就不必具有^ 2的復雜性。

為了簡化示例計算,我將兩個列表實現為包含整數,而不是類對象,但邏輯相同。 據我從您的示例了解,您想刪除例外列表中可用的所有posts對象。

    List<int> posts = new List<int>() { -3, -2, -1, 0, 1, 2, 3 };
    List<int> exceptions = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    IEnumerable<int> intersection = exceptions.Intersect(posts); /* returns the numbers that are both in the two lists */

    posts.RemoveAll(p => intersection.Contains(p)); /* remove the numbers from 'posts' that are intersected (1, 2, 3 are removed) */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM