I want to use an expression in another one:
Expression<Func<double, double>> f = x => x * x * 27 + blah ... expression with x;
Expression<Func<double, double>> g = y => 3 + 8 * f.Compile()(y) * y * blah... expression with y and f(y);
This will not work when sent to LINQ to SQL because f.Compile() is unknown to SQL.
How do you evaluate the expression f on the variable y without compiling it, but still using normal syntax to define g?
I don't want to have to define all of g with some unreadable Expression.Add/Expression.Multiply etc. statements.
Thanks.
Take a look at Calling functions in LINQ queries and LINQ Extensions project. CLinq part is irrelevant to your question, but it also includes LinqExt library, which is just what are you looking for. The same approach is also used by LinqKit which also provides other useful extensions for Linq.
Related
I have been learning about the lambda expression, I got happy when I finally can read/understand the => operator, it kind of means "where" to me
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b = a.FindAll(x => x>=5);
foreach (int x in b)
Console.WriteLine(x);
Reading the above line, personally makes sense to read it as "Find all x's from this list WHERE x is greater than or equal 5", very good.
But then I come across a different use of the lambda expression with the Select method.
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b1 = a.Select(x => x*2);
foreach (int x in b)
Console.WriteLine(x);
With this one, the previous way of reading this operator doesn't make sense, as to me this code does "For each x return x*2", which is very different "function" to what the same operator does in the previous case.
I understand that the difference is between .FindAll and .Select, different way of dealing with input and output parameters, but I am talking about the use of the operator => in the lambda expression.
There's no question in this question, so let's make one up.
Characterizing the lambda operator as "where" works when the lambda returns a bool and is used as a predicate to test a value. Is there a more general characterization of the lambda operator that makes sense in other contexts, such as projection?
Yes. Read the lambda operator as "goes to".
a.Select(x => x * 2);
"each x goes to x times two"
You can use that for predicates as well:
a.Where(x => x > 2);
"each x goes to 'is x greater than two?'"
But that's awkward. As you note, it is easier to think of this as "where" or "such that"
"each x such that x is greater than two"
Similarly
a.OrderBy(x => x.LastName)
"order each x by x goes to last name" is awkward. Just say "order each x by last name".
In short: the English language interpretation of the operator depends on the context. The formal interpretation of the operator is always the same: it simply describes a function.
The => operator has exactly the same meaning in both cases: it creates a function whose parameter is the thing on the left, and whose return value is the thing on the right.
You wrote in a comment that the x in the first case is not a parameter as you understand it. That's not correct; it is a parameter in both cases here.
Here's your first example, again:
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b = a.FindAll(x => x>=5);
foreach (int x in b)
Console.WriteLine(x);
If you wanted to write this without using lambda notation, you would define a function somewhere, like this...
static bool MyCondition(int x)
{
return x >= 5;
}
...and then use that function as the argument to FindAll:
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b = a.FindAll(MyCondition);
foreach (int x in b)
Console.WriteLine(x);
The lambda notation is a shorter notation which allows you to define the function right where you use it.
Likewise, if you wanted to write your second example without using lambda notation, you'd define a function elsewhere, like this...
static int MyOperation(int x)
{
return x * 2;
}
...and pass your function as the argument to Select, like this:
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b1 = a.Select(MyOperation);
foreach (int x in b)
Console.WriteLine(x);
Think of it this way:
Mathematics: f(x) = x + x
This is a mathematical function f that takes a number x and spits out its double.
Lambda: f = x => x + x C#'s way of defining the same function f.
Another example:
Mathematics: g(x, y) = x > y
g is a function that takes two numbers x and y and returns wether the former is greater than the latter.
Lambda: g = (x, y) => x > y C#'s way of defining the same function g.
Clearer now?
P.D: I've omitted talking about type inference and the type of the lambda's themselves; its an unnecessary distraction considering the context of this question.
I need to read from file mathematical expression and evaluate it's value. Example expression formats are as follow:
"5" - constant
"3.1415 * 0.25" - constant expressions
"{0} - 50" - expressions with value placeholders (String.Format())
"Abs({0} - 50)" - just like up but with mathematical functions
I was using so far NCalc which worked great until it had to deal with expressions like follow:
"3.0 * Abs({0} + 34)"
Unfortunately in example just above the result of following code:
var value = ReadValueFromSomewhere(); // Lets say it returns 125.75
var exprStr = ReadExpression(); // returns: "3.0 * Abs({0} + 34)"
var toEval = String.Format(exprStr, value);
var result = new NCCalc.Expression(toEval).Evaluate()
is following exception:
System.InvalidOperationException
Operator '*' can't be applied to operands of types 'double' and 'decimal'
NCalc.Numbers.Multiply(object, object)
NCalc.Domain.EvaluationVisitor.Visit(NCalc.Domain.BinaryExpression)
NCalc.Domain.BinaryExpression.Accept(NCalc.Domain.LogicalExpressionVisitor)
NCalc.Expression.Evaluate()
It seems like Abs() method returns decimal and NCalc can't handle doing calculations between double and decimal (propably bug?). So I would like to ask what alternative libraries I could use instead of NCalc? Or perhaps there is other workaround than expression:
"Abs(3.0) * Abs({0} + 34)"
?
What do you mean by "expressions with value placeholders"? Can you give more specific example? You can try mXparser - it works for Java and .NET.
Example of usage:
Expression e = new Expression("3.1415 * 0.25");
double v = e.calculate();
Follow mXparser tutorial.
Regards
Can you say what is the use of the ()=> and =>? I saw this in a code. I did not get any reference for this.
this.Dispatcher.BeginInvoke(()=>
{
//some thing..
};
=> is the lambda operator in C# and is read as "goes to". A lambda expression is an anonymous function and can be used to create a delegate.
Your example takes no arguments as indicated by the empty parens preceding the lambda operator. A lambda expression with one argument might look like this:
n => n.toString()
That expression would return the string representation of n, when invoked. A lambda expression can have multiple arguments as well, contained in parentheses:
(n, f) => n.toString(f)
A common use would be in a Func<T>:
Func<int, string> getString = n => n.toString();
int num = 7;
string numString = getString(num);
This is, of course, a silly example, but hopefully helps to illustrate its use.
This notation is that of a lambda expression which takes no argument. If the lambda expression made use of arguments they would be declared in the empty set of parenthesis as in say...
this.Dispatcher.BeginInvoke((x, y) => { do some' with x and/or y }, 12, somevar);
In a nutshell, lambda expressions allows creating "nameless" functions, right where they are needed.
In the example of the question, the BeginInvoke() method requires its first parameter to be a delegate (a "pointer to a method"), which is exactly what this lambda expression provides.
It's a lambda expression that has no parameters.
Check out this page http://codebetter.com/karlseguin/2008/11/27/back-to-basics-delegates-anonymous-methods-and-lambda-expressions/
If you don’t have any parameters, like in our example, you use empty
paranthesis:
() => {…}
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Lamda Explanation and what it is as well as a good example
What is the => token called?
I have seen this code:
myContext.SomeEntities.Single(x => x.code == code);
And I don´t know what does the => operator do.
Every search on google about the operator returns no results.
Thank you.
The => operator designates a Lambda Expression:
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:
static void Main(string[] args)
{
Func<int, int> func = x => x * x;
int j = func(5);
// j == 25
}
Lambda expressions, very cool.
http://msdn.microsoft.com/en-us/library/bb397687.aspx
This is defining a lambda. You can read it "x goes to x.code equals code," and it means that given x, return the result of the given comparison.
It signals that the code is a lambda expression.
More info:
http://msdn.microsoft.com/en-us/library/bb397687.aspx
They are related to lambda expressions.
You can read about Lambda Expressions here:
http://www.rvenables.com/2009/03/practical-introduction-to-lambda-expressions/
I will keep it really simple,
How do I get expression tree out of lambda??
or from query expression ?
You must assign the lambda to a different type:
// Gives you a delegate:
Func<int, int> f = x => x * 2;
// Gives you an expression tree:
Expression<Func<int, int>> g = x => x * 2;
The same goes for method arguments. However, once you've assigned such a lambda expression to a Func<> type, you can't get the expression tree back.
Konrad's reply is exact. You need to assign the lambda expression to Expression<Func<...>> in order for the compiler to generate the expression tree. If you get a lambda as a Func<...>, Action<...> or other delegate type, all you have is a bunch of IL instructions.
If you really need to be able to convert an IL-compiled lambda back into an expression tree, you'd have to decompile it (e.g. do what Lutz Roeder's Reflector tool does). I'd suggest having a look at the Cecil library, which provides advanced IL manipulation support and could save you quite some time.
Just to expand on Konrad's answer, and to correct Pierre, you can still generate an Expression from an IL-compiled lambda, though it's not terribly elegant. Augmenting Konrad's example:
// Gives you a lambda:
Func<int, int> f = x => x * 2;
// Gives you an expression tree:
Expression<Func<int, int>> g = x => f(x);