[英]using linq select from list data where
One Book
has list of Tag
objects. One
Book
有Tag
对象列表。 Using linq
I want to select list of books where any tag name contains specified filter. 使用
linq
我想选择任何标签名称包含指定过滤器的书籍列表。
string genre; // filter
List<Book> books = repository.GetBooks();
foreach(Book book in books.Where(x=>x.Tags.Any())) //I'm stuck here
you need to see if any tag name is equal to the filter: 你需要看看是否有任何标签名称等于过滤器:
books.Where(book => book.Tags.Any(tag => tag == genre))
or use Contains method: 或使用包含方法:
books.Where(book => book.Tags.Contains(genre))
assuming Tags
property returns a sequence of string
. 假设
Tags
属性返回一个string
序列。 If Tag
is a user-defined object, use: 如果
Tag
是用户定义的对象,请使用:
books.Where(book => book.Tags.Any(tag => tag.Name == genre))
Something like this should work 这样的事情应该有效
var results = books.Where(x => x.Tags.Any(t => t.Name == genre))
Or this: 或这个:
var results = books.Where(x => x.Tags.Select(t => t.Name).Contains(genre))
尝试以下方法
foreach(Book book in books.Where(x=>x.Tags.Any(t => t.Name == "tag-name")))
If Book.Tags
is a collection of Tag
objects, you should use Any
and pass lambda expression: 如果
Book.Tags
是Tag
对象的集合,则应使用Any
并传递lambda表达式:
foreach(Book book in books.Where(x=>x.Tags.Any(t => t.Name == filter)))
If Book.Tags
is a collection of string
s, you should use Contains
method: 如果
Book.Tags
是string
s的集合,则应使用Contains
方法:
foreach(Book book in books.Where(x=>x.Tags.Contains(filter)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.