linq to entities dynamic where clause as string
I want to filter data dynamically using linq to entities, by providing string expression to where clau开发者_StackOverflowse.
For example:
string filterExpr = "it.City='London'"
var ret1 = Contex.Customers.Where(filterExpr);
How can I do the same but this time to filter data that starts with some string?
if it's not possible to achieve using string, how can I build a appropriate Lambda expression?
(Also it's important to me to be able to filter by many parameters (OR/AND) )
I think what you might be looking for is Dynamic LINQ. Scott Guthrie posted this:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
It's not as fast as using the lambda syntax since they need to be compiled at run-time, but it might be your answer.
Public Shared Function getFilterStartsWith(Of T)(ByVal param As ParameterExpression, ByVal prop As MemberExpression, ByVal arg As Object) As Expression
Dim mi As MethodInfo = GetType(String).GetMethod("StartsWith", New Type() {GetType(String)}, Nothing)
Return Expression.Lambda(Of Func(Of T, Boolean))(LambdaExpression.[Call](prop, mi, Expression.Constant(arg, GetType(String))), param)
End Function
In C#:
public static Expression getFilterStartsWith<T>(ParameterExpression param, MemberExpression prop, object arg) {
MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }, null);
return Expression.Lambda<Func<T, bool>>(LambdaExpression.Call(prop, mi, Expression.Constant(arg, typeof(string))), param);
}
That's the function I'm using for startsWith in a solution I recently wrote. It turned out to be a huge pain because you can't use a Type variable as a parameter in ctype or DirectCast in vb and you can't do linq comparisons on a an object and a nullable object of the same type.
please try this:
var ret1 = contex.Customers.Where(x => x.it.City.StartsWith('l'));
HTH
Forget about "magic" strings, C# is meant to be strongly typed. One way or another You end up with a list of where's so the best way is to have them strongly typed.
public class Veg
{
public int Id { get; set; }
public string Name { get; set; }
public bool Fruit { get; set; }
}
enum Mode
{
One,
Two,
Three
}
static void Main()
{
Mode mode = Mode.One;
var data = new List<Veg>
{
new Veg{Id = 1, Name = "Apple", Fruit = true},
new Veg{Id = 2, Name = "Carrot", Fruit = false}
};
var dataSelect = data.Where(w => (mode == Mode.One && w.Fruit) || //only fruits
(mode == Mode.Two && !w.Fruit) || //only not fruits
(mode == Mode.Three)); //all of it
}
精彩评论