如何在字符串中创建C#中的表达式?
MongoDB C#驱动程序(或任何其他库)中有一些方法,它们仅期望表达式作为一个参数类似:
query.SortByDescending(x => x.Name) // sort by name for example
我想做的是将字段“名称”作为字符串接收,并且能够在运行时对其进行排序:
var sortBy = "Name";
query.SortByDescending(x => x."SortyBy") // something like this
即如何创建一个表达式为x => x。(sortby的值)
?
There are methods in MongoDB C# driver (or any other libraries) that expect an expression only as a parameter like:
query.SortByDescending(x => x.Name) // sort by name for example
What I would like to do is to receive the field "Name" as a string and be able to sort by it at runtime:
var sortBy = "Name";
query.SortByDescending(x => x."SortyBy") // something like this
i.e how to create an expression to be x => x.(value of sortBy)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题基本上的答案与您昨天的问题/a>。
答案本质上仅仅是
fieldDefinition< t>
是隐式从string
隐式铸造的原因,因此您可以在任何地方传递string
请参阅fieldDefinition< t>
参数。因此,我们可以使用
.sort
方法(因为这采用了sortDefinition< t>
),并使用builder< t> .sort.sort.descresend.descerding
采用fieldDefinition< telement>
并返回sortDefinition< t>
我们需要:我假设您的文档类型是
items
在这里,就像您昨天的问题一样。请注意,您在这里使用的文本名称必须匹配数据库中的名称,这不一定与文档的属性名称相同。如果您想使其更强大,那么您需要使用表达式树来为所讨论的属性生成表达式。
一种替代解决方案是构建
expression< func&lt
;
query = query.sortbydescending(i => i.name);
This question basically has the same answer as your question yesterday.
The reason the answer is essentially the same is simply that
FieldDefinition<T>
is implicitly castable fromstring
, so you can pass astring
anywhere you see aFieldDefinition<T>
argument.Therefore, we can use the
.Sort
method (since that takes aSortDefinition<T>
) and useBuilders<T>.Sort.Descending
which takes aFieldDefinition<TElement>
and returns theSortDefinition<T>
that we need:I'm assuming your document type is
Items
here as it was in your question yesterday.Note that the textual name you use here has to match the name in the database, which isn't necessarily the same as your document's property name. If you want to make it more robust, then you'll want to use expression trees to produce an expression for the property in question.
An alternative solution would be to build the
Expression<Func<T, TElement>>
thatSortByDescending
requires:As far as Mongo is concerned, this is no different to having written
query = query.SortByDescending(i => i.Name);