LINQ查询以查找所有标签? [英] LINQ Query to find all tags?

查看:59
本文介绍了LINQ查询以查找所有标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为Notes的用于管理文档的应用程序.就像博客一样,可以在Notes中搜索与一个或多个Tag(包含在Note.Tags集合属性中)匹配.标签具有名称"和"ID"属性,并且会对该ID进行匹配.用户可以指定要匹配的多个标签,在这种情况下,注释必须包含所有指定要匹配的标签.

I have an application that manages documents called Notes. Like a blog, Notes can be searched for matches against one or more Tags, which are contained in a Note.Tags collection property. A Tag has Name and ID properties, and matches are made against the ID. A user can specify multiple tags to match against, in which case a Note must contain all Tags specified to match.

我有一个非常复杂的LINQ查询,它使用扩展方法和循环来执行Note搜索.坦率地说,它具有真正的代码味道.我想用更简单的方法重写查询.我知道,如果我将Tag做成一个简单的字符串,则可以使用如下代码:

I have a very complex LINQ query to perform a Note search, with extension methods and looping. Quite frankly, it has a real code smell to it. I want to rewrite the query with something much simpler. I know that if I made the Tag a simple string, I could use something like this:

var matchingNotes = from n in myNotes
                    where n.Tags.All(tag => searchTags.Contains(tag))

如果我的模型使用带有ID的Tag对象,我可以做些简单的事情吗?查询是什么样的.可以用流利的语法编写吗?会是什么样?

Can I do something that simple if my model uses a Tag object with an ID? What would the query look like. Could it be written in fluent syntax? what would that look like?

推荐答案

我相信您可以在单个LINQ表达式中找到具有相关标签的注释:

I believe you can find notes that have the relevant tags in a single LINQ expression:

IQueryable<Note> query = ... // top part of query

query = query.Where(note => searchTags.All(st =>
    note.Tags.Any(notetag => notetag.Id == st.Id)));

不幸的是,没有与AllAny等效的流利语法",因此,您能做到的最好是

Unfortunately there is no "fluent syntax" equivalent for All and Any, so the best you can do there is

query = from note in query
        where searchTags.All(st =>
            note.Tags.Any(notetag => notetag.Id == st.Id))
        select note;

这也没有那么好.

这篇关于LINQ查询以查找所有标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆