因此,我尝试建立一个搜索系统,为此,我需要浏览列表中的每本“书”,并删除与给定的“体裁”不匹配的每本“书”。每本书都包含一个类别ID列表。
我使用了它,我确信它曾经可以工作,但是也许这是我的想象力...
books.RemoveAll(i => i.genres != null && !genres.All(x => i.genres.Any(y => x == y)));
有人知道如何实现此功能吗?
谢谢!
答案 0 :(得分:0)
听起来您是在说一本书具有多种类型,并且您想要基于一种类型的列表来过滤书籍列表,以使列表中的所有书籍在其类型列表中都具有所有类型。
此答案还假设Genre
类实现IComparable<Genre>
。在此示例中,genres
是List<string>
:
public class Book
{
public string Title;
public List<string> 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"}}
};
如果是这样,这应该可以解决问题:
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"