简体   繁体   English

使用linq从列表数据中选择

[英]using linq select from list data where

One Book has list of Tag objects. One BookTag对象列表。 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.TagsTag对象的集合,则应使用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.Tagsstring s的集合,则应使用Contains方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM