简体   繁体   English

如何在C#中过滤包含其他列表的列表?

[英]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.

相关问题 C# Linq 如何使用 object 的数据筛选列表并将结果存储在另一个列表中? - C# Linq How do I filter a list with the data of an object and store the result in another list? 在C#中,如何以一种方式将列表复制到另一个列表,使得在修改复制的列表时不会修改原始列表 - In C# How do I copy a list to another list in such a way that on modifying the copied list the original list is not modified 如何过滤C#中另一个列表的一部分的子列表 - How to filter a sub list which is part of another list in C# 如何在 LINQ C# 中使用另一个列表过滤列表 - How to filter a list using another list in LINQ C# 按另一个列表过滤列表 C# - Filter a list by another list C# 在C#中,如何使用另一个列表的StartsWith()条件过滤列表? - In C#, how can I filter a list using a StartsWith() condition of another list? 如何按 Razor 页面中的另一个列表过滤列表? - How do I filter a list by another list in a Razor page? 如何使用 linq c# 从另一个列表优化嵌套循环和过滤 - How do optimize nested loop and filter from another list using linq c# 将列表与另一个包含某些数据C#的列表同步 - Syncing List with another List containing Some data C# C# 列表加入列表并从另一个列表中过滤 - C# List Join List And Filter From Another List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM