What does => means? Here's a code snap:
Dispatcher.BeginInvoke((Action)(() => { trace.Add(response); }));
it's lambda expression which is the simplified syntax of anonymous delegate. it reads 'goes to'. equivalent to Dispatcher.BeginInvoke((Action)delegate() { trace.Add(response); });
=> is lambda expression operator which indicate that the code is lambda expression.
( param ) => expr(int x) = > { return x + 1 };
or
param => exprx=> x + 1;>
What is Lambda expression ?
* Lambda expression is replacement of the anonymous method avilable in C#2.0 Lambda
expression can do all thing which can be done by anonymous method.
* Lambda expression are sort and function consist of single line or block of statement.
Read more : Lambda Expressions
=> is an operator called Lambda Operator
It is used for creating a lambda expression
It's the lambda operator =>
It is a lambda operator which reads like "goes to"
This "=>" means the use of lambda expression syntax in C#.
This syntax is available since Visual Studio 2008 in .NET 3.5 (C# 3.0). This is the MSDN official documentation of lambda expression in C#.
The code above is the same as anonymous delegate in already available since C# 2.0
Your code:
Dispatcher.BeginInvoke((Action)(() => { trace.Add(response); }));
is translated into:
Dispatcher.BeginInvoke(new delegate () { trace.Add(response); });
Those two codes essentially have the same semantics.
It's worth noting that a single expression lambda doesn't need the {} around the body, nor does it need a semicolon, so you can simplify your code (slightly) to.
Dispatcher.BeginInvoke((Action)(() => trace.Add(response) ));
Related
Since we can:
Expression<Func<int, bool>> predicate = x => x > 5;
var result = Enumerable.Range(0,10).Where(predicate.Compile());
How can I:
Func<int,bool> predicate = x => x > 5;
Expression<Func<int,bool>> exp = predicate.Decompile();
That is, I want to get the corresponding Expression of the Func. Is it possible?
There is no magic Decompile() for a delegate instance, short of deconstructing the IL (perhaps with mono.cecil). If you want an expression tree, you'll have to start with an expression tree, so have Expression<Func<int, bool>> througout.
As an edge case, you can get basic method delegate information from the delegate's .Method (the MethodInfo) and .Target (the arg0) - however, for most scenarios involving a lambda or anonymous method this will point at the compiler-generate method on the capture class, so won't really help you much. It is pretty much limited to scenarios like:
Func<string,int> parse = int.Parse;
Pass the lambda to a method that accepts an Expression<> and the C# compiler will pass you an expression tree at runtime. However this only works if you pass the lambda directly, not if you try to pass a delegate instance created from a lambda.
var exp = Decompile(x => x > 5);
public Expression<Func<int, bool>> Decompile(Expression<Func<int, bool>> exp)
{
return exp;
}
The closest option I've found for decompiling a delegate instance is detailed in this blog post from Jean-Baptiste Evain who works on the Mono team. He uses the excellent Mono.Cecil project to decompile the IL into a custom AST, then he maps it as best as possible into LINQ expressions.
You can try to use my library:
https://github.com/ashmind/expressive
Though it may not work as is for results of Compile(), since it is a DynamicMethod and getting IL of it is not straightforward. If you implement your own IManagedMethod implementation for DynamicMethod, though, it should just work.
I plan to implement DynamicMethod adapters, but do not yet know when.
You can’t decompile the delegate, but you can certainly create a new expression tree that simply calls the delegate:
Func<int, bool> predicate = x => x > 5;
Expression<Func<int, bool>> exp = x => predicate(x);
I am newbie to EF how to use and - or in where clause in the entity framework
HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL attendanceDeviceShutdownTbl =
context.HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL
.FirstOrDefault(x => x.Device_ID.Equals(model.DeviceId) &&
x=>x.Device_Name=model.DeviceName);
the above code will not work but how can I make it works.
Expression lambda has following syntax param => expression. I.e. its like simple method, which have input parameter(s) and body. You define parameters only once and then use them in body of method or lambda:
HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL attendanceDeviceShutdownTbl =
context.HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL.FirstOrDefault(x =>
x.Device_ID.Equals(model.DeviceId) && x.Device_Name == model.DeviceName);
In this case you have single parameter x which goes to anonymous function body. Body is an expression which should return boolean value and (usually) use parameter x. In your case lambda body should be
x.Device_ID.Equals(model.DeviceId) && x.Device_Name == model.DeviceName
Suggested reading: Lambda Expressions (C# Programming Guide). Also note == is a comparison operator. = is an assignment operator. Do not mix up with them.
I am trying to combine a multiple selection with a lambda function into an lambda expression. How do I do that? I know the last line is wrong, but giving you an idea of what I mean.
Func<Event, bool> where = null;
if (!string.IsNullOrWhiteSpace(searchToken))
where = q => q.Name.ToUpper().Contains(searchToken.ToUpper());
where += q => q.Hidden = false;
Expression<Func<Event, bool>> where1 = q => where; <-- Erroring
I suspect you want PredicateBuilder. (The source is available on that page.) You'd use it like this:
var predicate = q => !q.Hidden;
if (!string.IsNullOrWhiteSpace(searchToken))
{
predicate = predicate.And(q => q.Name.ToUpper()
.Contains(searchToken.ToUpper());
}
return predicate;
That's assuming you want to "and" the conditions - you never made that clear...
Note that that is not a good way to compare in a case-insensitive way, either. If you could tell us what's going to consume the query (e.g. LINQ to SQL, LINQ to EF) we could suggest a provider-compatible way of performing a case-insensitive query.
Look at http://msdn.microsoft.com/en-us/library/bb882637.aspx. How to use expression trees to build dynamic queries.
AFAIK when using Expression <> like that the expression must be known in compile time, because the compiler then build AST abstract syntax three and stores it as data in your Expression <> instance.
This line of code that tries to assign a lambda expression to a LambaExpression typed variable,
LambdaExpression expr = n => n;
it fails with compile error message:
Cannot convert lambda
expression to type
'System.Linq.Expressions.LambdaExpression'
because it is not a delegate
type
So it needs to be a delegate type. Conceptually it seems odd to me because I can build out a LambdaExpression instance using a factory method like so.
Factory Lambda from MSDN
LambdaExpression lambdaExpr = Expression.Lambda(
Expression.Add(
paramExpr,
Expression.Constant(1)
),
new List<ParameterExpression>() { paramExpr }
);
and that's not a delegate type.
It makes we wonder why lambda to LambaExpression cannot work?
Well, this does work:
Expression<Func<int, int>> exp = n => n;
LambdaExpression lambda = exp;
Note that Expression<TDelegate> derives from LambdaExpression.
I think the reason you can't just use LambdaExpression as the type is that then the type of n (in your example) could not be inferred.
Consider the fact that you also can't do this, for basically the same reason:
// What is this? An Action? A ThreadStart? What?
Delegate d = () => Console.WriteLine("Hi!");
Whereas you can do this:
Action a = () => Console.WriteLine("Hi!");
Delegate d = a;
It's essentially the same thing.
Because LambdaExpression is a way to generate lambda expressions at runtime, where as n => n gets converted to a generated class at compile time.
In short: they are two different things to do the same thing, but can't be used together.
To quote MSDN
The LambdaExpression type represents a lambda expression in the form of an expression tree. The Expression type, which derives from LambdaExpression and captures the type of the lambda expression more explicitly, can also be used to represent a lambda expression. At runtime, an expression tree node that represents a lambda expression is always of type Expression.
The value of the NodeType property of a LambdaExpression is Lambda.
Use the Lambda factory methods to create a LambdaExpression object.
Read carefully what errror message is saying. LambdaExpression is not a delegate. It is normal class. Read http://msdn.microsoft.com/en-us/library/system.linq.expressions.lambdaexpression.aspx. Because it has Lambda in name doesn't mean it is same as 'true' lambda.
Is it mandatory that lambda expression need to use when LINQ will be used, or are lambda expressions optional?
In lambda expressions, the sign => is always used. What does it mean?
customers.Where(c => c.City == "London");
Here c => is used but why?
What kind of meaning of using c =>. Please discuss in detail because I don't know lambda.
No, you don't have to use a lambda expression. For example, your Where example could be written as:
private static bool IsLondon(Customer customer)
{
return customer.City == "London";
}
...
var londoners = customers.Where(IsLondon);
That's assuming LINQ to Objects, of course. For LINQ to SQL etc, you'd need to build an expression tree.
As to why "=>" is always used in a lambda expression, that's simply because that's the way the operator is written - it's like asking why "+" is used for addition.
A lambda expression of "c => ..." is effectively giving the lambda expression a parameter called c... in this case generic type inference provides the type of c. The body provides either an action to perform or some calculation to return a value based on c.
A full-blown description of lambda expressions is beyond the scope of this answer. As a blatant plug for my book, however, they're covered in detail in chapter 9 of C# in Depth.
The lambda expression
c => c.City == "London"
is shorthand for something like
bool IsCustomerInLondon(Customer c)
{
return (c.City == "London");
}
It's just a very concise way of writing a simple function that returns a value. It's called an "anonymous function" because it's never assigned a name or a formal definition (the parameter types and the return type are inferred from the context).
(Actually, it's not just shorthand; lambda expressions are related to some other constructs called closures, which are very cool and powerful tools.)
Think about lambdas as anonymous of functions.
I'll try to explain it with following code.
public bool IsLondon(Customer customer)
{
return customer.City == "London";
}
Now we strip down function name and get rid of braces:
public bool Customer customer
return customer.City == "London";
We don't need return type, because compiler is able to deduce type from expression:
customer.City == "London";
In the same manner compiler knows about input type, so we don't need to specify it.
So basically, what we left with is
customer
return customer.City == "London";
And lambda syntax in c# is basically:
(parameter list) => "expression"
You can also write "multi-line" expressions, but then you have to surround your code with curly braces. Also you will need to use "return" statement, like you usually do.
Jon already answered,
but I'd like to add this.
In the example you have given, imagine Linq looping over all customers,
and c is simply a reference to each item in the enumerable:
var result = new List<Customer>();
foreach(var c in customers)
{
if (c.City == "London")
result.Add(c);
}
return result;
It's a variable like any other, it does not have to be a single named one,
but it's just a convention of some sort.
you do not need to use lambda expressions on Lİnq to sql or Entities; here is an alternative way of your code;
you code :
customers.Where(c => c.City == "London");
the other way;
var query = from cs in customers
where cs.City == "London"
select cs;
this is the another way. it is up to you.
Lambda and linq are quite separate. You can use one without using the other (there are parts of linq that depend on lambda expressions, but we want to keep it simple :-) )
A lambda expression is an anonymous
function that can contain expressions
and statements, and can be used to
create delegates or expression tree
types.
This was from MSDN. (http://msdn.microsoft.com/en-us/library/bb397687.aspx )
To make it short (it's much more complex) you can use a lambda expression to make a local function. what you put before the => (in your example the c) will be the parameter of the function. The return type is "discovered" by the C# compiler.
c => c.City == "London" is nearly equivalent to:
delegate (TheObjectTypeOfC c) {
return c.City == London
};
(the difference is that some lambda expression are delegates and also expressions, but please ignore this, you won't need it for some time)
If/when the compiler isn't able to infer the types of the parameters, you can force them: (MyObject p) => p.SomeProperty != null. Here you are telling the compiler that p is a parameter.
While here I showed you what are called "expression lambdas", you can even do "statement lambdas":
p => {
for (int i = 0; i < 10; i++) {
if (p.SomeProperty == 0) {
return true;
}
}
return false;
}
(I won't tell you what are the "behind the scenes" differences between expression lambdas and statement lambdas. If you want to know them, read the msdn page I pointed before)
No it is not necessary at all.
We have two ways to write LINQ queries.
One is query method and other is builder method. You only need to put lambda expression in case of builder method.
For example, if we want to find all those students from some Students object that have more marks than 70.
but we can do this thing in LINQ with following syntax
var data = from p in stdList
where p.marks > 70
select p;
or
var data = stdList.Where(p=>p.marks > 70);
later approach is builder method, in Where function, we are passing lambda expressions.
Lambda expressions are just short cuts of doing things you can always use LINQ queries but if you want to avoid whole query syntax for just applying a simple condition you can just use LINQ builder methods (which asks for lambda expressions) in lambda expressions, you always define some alias and then perform your operation.
As far as => operator is concerned, It works just like assignment operator.
For example:
(p) => p.Gender == “F”
It means “All persons p, such that person’s Gender is F”
In some literature this is called “predicate”. Another literature terminology is “Projection”
(p) => p.Gender ? “F” : “Female”
“Each person p becomes string “Female” if Gender is “F””
This is projection, it uses ternary operator.
Although i explained with very basic examples but i hope this would help you . . . :)