i want to replace operator(==, >= ,>...) in the clause where of linq lambda with parameter passed in method
the method:
public IEnumerable<Localisation> GetByFiltre(string filter, string valeurDate1)
/*
filter has the value of an operator:
>
==
!=
>=
<=
*/
DateTime dt = Convert.ToDateTime(valeurDate1);
var mod = from o in new GpsContext().Locals.Where(loc => loc.Date == dt)
i want to replace == in the clause where with the parameter filter to obtain something like this
var mod = from o in new GpsContext().Locals.Where(loc => loc.Date filter dt)
any body knows how to make it work ?
There is a good library for parsing strings into Lamdba expressions described here
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
and downloadable here
http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspx
It has a pretty good expression syntax that lets you express quite a lot of different queries and operations.
Be aware though that depending on the query, you may lose some type safety. Where operations are OK, but any kind of projection where the Select lambda is parsed from a string cannot be inferred by the compiler. This measn you end up with non-generic IQueryables rather than generically typed ones. Sometimes this is OK, but it does prevent you from using generic extension methods later on in the query.
Edit to clarify situation with non-generic query operations: The library contains a set of non-generic versions of the query extension methods that take string representations of expressions and operate on non-generic IQueryable. If you look at the code, it is pretty easy to see how to write these if the one you want isn't there. For example, I needed to do a non-generic Join and it only took a couple of hours.
And the filter should contain "==", ">=" etc? You can analyse filter string in a traditional way:
You could pass in the function that is your where clause, e.g.
And call it with:
I think it's better to make dictionary out of string filters and corresponding delegates.
I found a solution to your problem that works like this:
You can use any
ExpressionType
- equals, less than, greater than, etc. and it will get translated to T-SQL if possible (so the filtering will be done on the server). It will also work in-memory onIEnumerables
.Here's the code: