Reputation: 1022
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
Upvotes: 3
Views: 9432
Reputation: 125650
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)))
Upvotes: 1
Reputation: 23646
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))
Upvotes: 6
Reputation: 3937
try the following
foreach(Book book in books.Where(x=>x.Tags.Any(t => t.Name == "tag-name")))
Upvotes: 1
Reputation: 149078
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))
Upvotes: 2