[英]How do I filter a list containing another list in C#?
I have two classes connected via a one-to-many relationship: 我有两个通过一对多关系连接的类:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public string Synopsis { get; set; }
public IList<Tag> Tags { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
}
How do I find all movies containing a given string? 如何找到包含给定字符串的所有电影? I manage as long as I do not dive into the tags:
只要我不深入标签,我就会管理:
var result = movies.Where(m => m.Title.Contains(searchString) |
m.Synopsis.Contains(searchString));
Here is some pseudo code, only working in my dreams: 这是一些伪代码,只在我的梦中工作:
var result = movies.Where(m => m.Title.Contains(searchString) |
m.Synopsis.Contains(searchString) |
m.Tags.Name.Contains(searchString));
// Cannot access Name property of Tags like this
What is the right way to do it? 做正确的方法是什么?
You cannot access the properties of a Tag
because you do not hold a reference to Tag
but to a collection of tags. 您无法访问
Tag
的属性,因为您没有对Tag
的引用,而是对标记集合的引用。 Therefore you need to use linq's .Any
to query: 因此你需要使用linq的
.Any
来查询:
Determines whether any element of a sequence satisfies a condition.
确定序列的任何元素是否满足条件。
So: 所以:
var result = movies.Where(m => m.Title.Contains(searchString) |
m.Synopsis.Contains(searchString) |
m.Tags.Any(t => t.Name.Contains(searchString)));
Also consider using ||
还要考虑使用
||
operator instead of |
运算符而不是
|
operator . 运营商 。 Both perform a logical
OR
but the former will do it lazily (ie stop as soon as it runs into a true
). 两者都执行逻辑
OR
但前者会懒惰地执行(即一旦遇到true
就停止)。 Read more: C# 'or' operator? 阅读更多: C#'或'运营商? and
和
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.