简体   繁体   English

动态使用查询语法创建LINQ查询表达式的方法有哪些?

[英]What are the ways to create the LINQ query expression using query syntax dynamically?

What are the possible ways to create a LINQ expression dynamically, but using the query syntax ? 动态但使用查询语法创建LINQ表达式的可能方法是什么? Is the query syntax a C# thing only, and if so, is the only viable way of creating such expressions using Roslyn dynamic compilation? 查询语法是否仅是C#,如果是,那么使用Roslyn动态编译创建此类表达式的唯一可行方法是吗?

When writing LINQ expressions manually, I find them more natural when written using method chaining syntax, for example ctx.Foo.Where(foo => foo.Type.Name == "Bar") but there are some cases where I would need to write them like this: 手动编写LINQ表达式时,使用方法链接语法编写时会发现它们更自然,例如ctx.Foo.Where(foo => foo.Type.Name == "Bar")但是在某些情况下,我需要像这样写它们:

from foo in ctx.Foo
join fooType in ctx.Types on foo.TypeId equals fooType.Id
where fooType.Name == "Bar"

I love how expression trees ensure type safety when creating expressions dynamically, but how would one create expressions using the query syntax? 我喜欢表达式树如何在动态创建表达式时确保类型安全,但是如何使用查询语法创建表达式?

Thanks everyone for your comments. 感谢大家的意见。 So it turns out it's not possible to do this because query syntax is just a C# language syntactic sugar. 事实证明,这样做是不可能的,因为查询语法只是C#语言的语法糖。

Additionally, if someone else stumbles upon this question, take a look at the excellent answer by @Gert: https://stackoverflow.com/a/15599143/828023 此外,如果其他人偶然发现了这个问题,请查看@Gert提供的出色答案: https ://stackoverflow.com/a/15599143/828023

That answer explains that the query syntax is "sugar", while the method syntax shows what really goes on under the hood, where for example join x in y on z equals x.something into somethingElse is actually a GroupJoin method call and there is no way to express this with expression trees without actually calling GroupJoin . 这个问题的答案解释说,查询语法是“糖”,而方法的语法显示真正的推移引擎盖,其中,例如下join x in y on z equals x.something into somethingElse实际上是一种GroupJoin方法调用并没有用表达式树表达这种方式而无需实际调用GroupJoin

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

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