user2783193
user2783193

Reputation: 1022

using linq select from list data where

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

Answers (4)

MarcinJuraszek
MarcinJuraszek

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

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

Upvotes: 1

Ilya Ivanov
Ilya Ivanov

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

sjkm
sjkm

Reputation: 3937

try the following

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

Upvotes: 1

p.s.w.g
p.s.w.g

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

Related Questions