简体   繁体   中英

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 ? Is the query syntax a C# thing only, and if so, is the only viable way of creating such expressions using Roslyn dynamic compilation?

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:

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.

Additionally, if someone else stumbles upon this question, take a look at the excellent answer by @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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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