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?
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.
Using list.list. clear() is the recommended solution in Python 3 to remove all items from the list.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With