c# - 如何删除列表中包含的列表不包含所有给定值的所有实例?请帮忙
问题描述
因此,我正在尝试建立一个搜索系统,为此我需要遍历列表中的每一本“书”,并删除与给定“流派”不匹配的每一本。每本书都包含一个类型 ID 的列表。
我用过这个,我确信它曾经有效,但也许这是我的想象......
books.RemoveAll(i => i.genres != null && !genres.All(x => i.genres.Any(y => x == y)));
有谁知道如何实现这个功能?
谢谢!
解决方案
听起来您是在说一本书有很多流派,并且您想根据流派列表过滤书籍列表,以便列表中的所有书籍在流派列表中都有其所有流派。
这个答案还假设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"
推荐阅读
- python - 在 pycharm 控制台中更新文本
- typescript - 打字稿类型条件导致不可分配错误
- python - 通过使用变量在 .format() 中设置精度
- jenkins - 如何将 Gradle 参数发送给 Jenkins?
- python - 如何按子列表的长度对 3 个或更多列表列表进行排序
- node.js - 当您删除用户时,让用户帖子在节点 js 中也被删除
- mongodb - MongoDB:连接到 127.0.0.1:27017 时出错,无法建立连接,因为目标机器主动拒绝它
- python - 为什么显示 io.UnsupportedOperation: not writable
- java - “变量可能尚未初始化” - 但我希望用户输入填写变量
- javascript - Three.js:场景的子节点似乎与场景子节点的子节点具有不同的矩阵位置?