I'm in the process of creating a more elaborate filtering system for this huge project of ours. One of the main predicates is being able to pass comparations through a string parameter. This expresses in the following form: ">50" or "5-10" or "<123.2"
What I have (as an example to illustrate)
ViewModel:
TotalCost (string) (value: "<50")
Required (string) (value: "5-10")
EF Model:
TotalCost (double)
Required(double)
Expression that I would like to use:
model => model.Where(field => field.TotalCost.Compare(viewModel.TotalCost) && field.Required.Compare(viewModel.Required));
Expression that I would like to receive:
model => model.Where(field => field.TotalCost < 50 && field.Required > 5 && field.Required < 10);
Or something akin to that
However... I have no idea where to start. I've narrowed it down to
public static Expression Compare<T>(this Expression<Func<T, bool>> value, string compare)
It may not be even correct, but this is about all I have. The comparison builder is not the issue, that's the easy bit. The hard part is actually returning the expression. I have never tried returning expressions as function values. So basically what I need to keep, is the field and return a comparison expression, pretty much.
Any help? :x
Update:
Alas this doesn't solve my problem. It may be because I have been up for the past 23 hours, but I have not the slightest clue on how to make it into an extension method. As I said, what I'd like... is basically a way to write:
var ex = new ExTest();
var items = ex.Repo.Items.Where(x => x.Cost.Compare("<50"));
The way I shaped out that function (probably completely wrong) is
public static Expression<Func<decimal, bool>> Compare(string arg)
{
if (arg.Contains("<"))
return d => d < int.Parse(arg);
return d => d > int.Parse(arg);
}
It's missing the "this -something- value" to compare to in first place, and I haven't managed to figure out yet how to have it be able to get an expression input... as for ReSharper, it suggests me to convert it to boolean instead...
My head's full of fluff at the moment...
Update 2:
I managed to figure out a way to have a piece of code that works in a memory repository on a console application. I'm yet to try it with Entity Framework though.
public static bool Compare(this double val, string arg)
{
var arg2 = arg.Replace("<", "").Replace(">", "");
if (arg.Contains("<"))
return val < double.Parse(arg2);
return val > double.Parse(arg2);
}
However, I highly doubt that's what I'm after
Update 3:
Right, after sitting down and looking through lambda expressions again, before the last answer, I came up with something akin to the following, it doesn't fill in the exact requirements of "Compare()" but It's an 'overload-ish' Where method:
public static IQueryable<T> WhereExpression<T>(this IQueryable<T> queryable, Expression<Func<T, double>> predicate, string arg)
{
var lambda =
Expression.Lambda<Func<T, bool>>(Expression.LessThan(predicate.Body, Expression.Constant(double.Parse(50.ToString()))));
return queryable.Where(lambda);
}
However, despite to my eyes, everything seeming logical, I get runtime exception of:
System.ArgumentException was unhandled
Message=Incorrect number of parameters supplied for lambda declaration
Source=System.Core
StackTrace:
at System.Linq.Expressions.Expression.ValidateLambdaArgs(Type delegateType, Expression& body, ReadOnlyCollection`1 parameters)
at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, String name, Boolean tailCall, IEnumerable`1 parameters)
at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, Boolean tailCall, IEnumerable`1 parameters)
at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, ParameterExpression[] parameters)
This being the culprit line obviously:
var lambda =
Expression.Lambda<Func<T, bool>>(Expression.LessThan(predicate.Body, Expression.Constant(double.Parse(50.ToString()))));
I'm very close to the solution. If I can get that error off my back, I believe EF should be capable of translating that into SQL. Otherwise... well, the last response will probably go.
the operator => has nothing to do with linq - it's a lambda expression. It's used to create anonymous functions, so you don't need to create a full function for every small thing.
Both yields the same result because query expressions are translated into their lambda expressions before they're compiled. So performance-wise, there's no difference whatsoever between the two.
Basically, Lambda expression is a more concise syntax of anonymous method. It is just a new way to write anonymous methods. At compile time all the lambda expressions are converted into anonymous methods according to lambda expression conversion rules.
To convert a lambda expression to a named methodMove to the labda expression you want to convert. From the Refactor menu of the VisualAid choose To Named Method. Telerik® JustCode™ will replace the lambda expression with a method group and will add a new method.
To generate expression, that would be translated to SQL (eSQL) you should generate Expression
manually. Here is example for GreaterThan filter creating, other filters can be made with similar technique.
static Expression<Func<T, bool>> CreateGreaterThanExpression<T>(Expression<Func<T, decimal>> fieldExtractor, decimal value)
{
var xPar = Expression.Parameter(typeof(T), "x");
var x = new ParameterRebinder(xPar);
var getter = (MemberExpression)x.Visit(fieldExtractor.Body);
var resultBody = Expression.GreaterThan(getter, Expression.Constant(value, typeof(decimal)));
return Expression.Lambda<Func<T, bool>>(resultBody, xPar);
}
private sealed class ParameterRebinder : ExpressionVisitor
{
private readonly ParameterExpression _parameter;
public ParameterRebinder(ParameterExpression parameter)
{ this._parameter = parameter; }
protected override Expression VisitParameter(ParameterExpression p)
{ return base.VisitParameter(this._parameter); }
}
Here is the example of usage. (Assume, that we have StackEntites
EF context with entity set TestEnitities of TestEntity
entities)
static void Main(string[] args)
{
using (var ents = new StackEntities())
{
var filter = CreateGreaterThanExpression<TestEnitity>(x => x.SortProperty, 3);
var items = ents.TestEnitities.Where(filter).ToArray();
}
}
Update:
For your creation of complex expression you may use code like this:
(Assume have already made CreateLessThanExpression
and CreateBetweenExpression
functions)
static Expression<Func<T, bool>> CreateFilterFromString<T>(Expression<Func<T, decimal>> fieldExtractor, string text)
{
var greaterOrLessRegex = new Regex(@"^\s*(?<sign>\>|\<)\s*(?<number>\d+(\.\d+){0,1})\s*$");
var match = greaterOrLessRegex.Match(text);
if (match.Success)
{
var number = decimal.Parse(match.Result("${number}"));
var sign = match.Result("${sign}");
switch (sign)
{
case ">":
return CreateGreaterThanExpression(fieldExtractor, number);
case "<":
return CreateLessThanExpression(fieldExtractor, number);
default:
throw new Exception("Bad Sign!");
}
}
var betweenRegex = new Regex(@"^\s*(?<number1>\d+(\.\d+){0,1})\s*-\s*(?<number2>\d+(\.\d+){0,1})\s*$");
match = betweenRegex.Match(text);
if (match.Success)
{
var number1 = decimal.Parse(match.Result("${number1}"));
var number2 = decimal.Parse(match.Result("${number2}"));
return CreateBetweenExpression(fieldExtractor, number1, number2);
}
throw new Exception("Bad filter Format!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With