Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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. How to do this in LINQ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...