Build Linq query on the fly

  • Thread starter Thread starter GiJeet
  • Start date Start date
G

GiJeet

Hello, in SQL we can build a SQL query on the fly by appending strings
of commands then use the Exec() command to execute the query. Is
there a way to do the same with C# and Linq?

Thanks,
G
 
Hello, in SQL we can build a SQL query on the fly by appending strings
of commands then use the Exec() command to execute the query.  Is
there a way to do the same with C# and Linq?

Yes, and in a far better way than appending strings - you get to work
directly with AST of the query. Look at the Expression<T> class, and
the associated Expression helper static class. All IQueryable
operations actually take Expression<T> instances - they're implicitly
created for you when you use lambdas or LINQ syntactic sugar, but you
can just as well build them yourself as needed.
 
Yes, and in a far better way than appending strings - you get to work
directly with AST of the query. Look at the Expression<T> class, and
the associated Expression helper static class. All IQueryable
operations actually take Expression<T> instances - they're implicitly
created for you when you use lambdas or LINQ syntactic sugar, but you
can just as well build them yourself as needed.

Thanks. Can you point me to some examples. I learn better by seeing
examples. Thanks.
 
Thanks.  Can you point me to some examples.  I learn better by seeing
examples.  Thanks.

This is a general explanation of expression trees:

http://blogs.msdn.com/charlie/archive/2008/01/31/expression-tree-basics..aspx

This one is more detailed, and includes a brief sample on hand-
building them:

http://msdn.microsoft.com/en-us/library/bb397951.aspx

This one is a sample specifically covering your case (dynamic query):

http://msdn.microsoft.com/en-us/library/bb882637.aspx
 
Pavel Minaev said:
Yes, and in a far better way than appending strings - you get to work

"Better" is a loaded word. It couldn't get much simpler than appending
strings. :-)

Michael
 
Back
Top