3

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

4 Answers 4

6

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))
Sign up to request clarification or add additional context in comments.

Comments

2

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))

Comments

1

try the following

foreach(Book book in books.Where(x=>x.Tags.Any(t => t.Name == "tag-name"))) 

Comments

1

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 strings, you should use Contains method:

foreach(Book book in books.Where(x=>x.Tags.Contains(filter)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.