Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items of list from another lists with criteria

Tags:

c#

.net

list

linq

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?

like image 865
developer Avatar asked Nov 30 '10 10:11

developer


People also ask

How do you remove an element from one list to another list?

To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do you delete all items from one list to another in Python?

Using list.list. clear() is the recommended solution in Python 3 to remove all items from the list.

How do I remove a list from a nested list in Python?

Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.

How do I remove a list from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.


1 Answers

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

like image 76
Jon Skeet Avatar answered Sep 21 '22 17:09

Jon Skeet