One Book
has list of Tag
objects. Using linq
I want to select list of books where any tag name contains specified filter.
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
. If Tag
is a user-defined object, use:
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:
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:
foreach(Book book in books.Where(x=>x.Tags.Contains(filter)))
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.