![](/img/trans.png)
[英]C# Linq How do I filter a list with the data of an object and store the result in another list?
[英]How do I filter a list containing another list in C#?
我有兩個通過一對多關系連接的類:
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; }
}
如何找到包含給定字符串的所有電影? 只要我不深入標簽,我就會管理:
var result = movies.Where(m => m.Title.Contains(searchString) |
m.Synopsis.Contains(searchString));
這是一些偽代碼,只在我的夢中工作:
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
做正確的方法是什么?
您無法訪問Tag
的屬性,因為您沒有對Tag
的引用,而是對標記集合的引用。 因此你需要使用linq的.Any
來查詢:
確定序列的任何元素是否滿足條件。
所以:
var result = movies.Where(m => m.Title.Contains(searchString) |
m.Synopsis.Contains(searchString) |
m.Tags.Any(t => t.Name.Contains(searchString)));
還要考慮使用||
運算符而不是|
運營商 。 兩者都執行邏輯OR
但前者會懶惰地執行(即一旦遇到true
就停止)。 閱讀更多: C#'或'運營商? 和
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.