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. Therefore you need to use linq's .Any
to query:
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
). Read more: C# 'or' operator? and
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.