首页 > 解决方案 > 如何删除列表中包含的列表不包含所有给定值的所有实例?请帮忙

问题描述

因此,我正在尝试建立一个搜索系统,为此我需要遍历列表中的每一本“书”,并删除与给定“流派”不匹配的每一本。每本书都包含一个类型 ID 的列表。

我用过这个,我确信它曾经有效,但也许这是我的想象......

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

有谁知道如何实现这个功能?

谢谢!

标签: c#asp.netlinq

解决方案


听起来您是在说一本书有很多流派,并且您想根据流派列表过滤书籍列表,以便列表中的所有书籍在流派列表中都有其所有流派。

这个答案还假设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"

推荐阅读