How to remove all instances inside a list where a contained list does not contain all values given? help please

So I am trying to set up a searching system, for which I need to go through each ‘book’ in a list and remove each one that does not match the given ‘genres’. each book contains a list of genre ID’s.

I used this and I am sure it used to work but maybe it was my imagination…

books.RemoveAll(i => i.genres != null && !genres.All(x => i.genres.Any(y => x == y)));

does anyone know how to implament this feature?

Thank you!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It sounds like you’re saying that a book has many genres, and you want to filter a list of books based on a list of genres such that all books in the list have all their genres in the genre list.

This answer is also assuming that the Genre class implements IComparable<Genre>. In this example genres is a List<string>:

public class Book
{
    public string Title;
    public List<string> Genres;
}

Then for sample data, we can create a list of books and a list of genres:

var genres = new List<string> {"Horror", "Action", "Adventure"};

var books = new List<Book>
{
    new Book {Title = "The Shining", Genres = new List<string> {"Horror", "Adventure"}},
    new Book {Title = "Sahara", Genres = new List<string> {"Action", "Adventure"}},
    new Book {Title = "The Odds", Genres = new List<string> {"Action", "Comedy"}}
};

If that’s the case, this should do the trick:

books.RemoveAll(book =>
    book.Genres != null &&
    book.Genres.Any(genre => !genres.Contains(genre)));

// The last book is removed from the list, because 'genres' doesn't contain "Comedy"


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x