This question already has answers here:
Why would you use Expression<Func<T>> rather than Func<T>?
(12 answers)
Closed 3 years ago.
I am starting to see methods like the one below used more and more, but it's a concept that I don't fully understand.
public virtual Task<List<T>> GetAsync(Expression<Func<T, bool>> exp)
{
using (var conn = _factory.OpenDbConnection())
{
return conn.SelectAsync(exp);
}
}
Can someone help me translate the method parameter there that is an Expression? Like explain it as how it differs from a standard instance parameter?
These are called Expression Trees (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/).
Basically it's a lamdba that can be translated to another platform, from the looks of it some kind of database in your case. This function would be translated (by a library) to SQL and then executed in the database.
Within the code of your program you would generally only need lambdas (Func<>), but in some cases you need an Expression Tree. Besides your example, sometimes you need a dynamically constructed function which can be done using these.
General information on lambdas can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions
Related
This question already has an answer here:
LINQ - Query syntax vs method chains & lambda [closed]
(1 answer)
Closed 5 years ago.
In some cases I see LINQ written this way:
L.Select(_ => _.A).Where(...)
and in some other cases, I see this:
A = from B in C where (...)
Do these two syntaxes have different names?
I understand both, but they seem to be referred to as LINQ so I am a bit confused.
The first one is Method Syntax or Method extension syntax or Fluent
The second one is Query Syntax or Query Expression Syntax
This question already has answers here:
Lambda for getter and setter of property
(3 answers)
Closed 5 years ago.
I've read some code in setting property for a class like below
private int id;
public int ID {
get=>id;
set=>id=value;
}
and it works. But I'm totally confused by the lambda syntax.
I know that lambda expression would be (input-parameters) => expression.
how could it drop brackets in the left.
I've search the answer in google but not found. the likely answer would be that get&set should be equal to delegate, but I've no idea about this. Does someone has document about this?
You could find the usage of lambda of C# here
Quoted here:
To create a lambda expression, you specify input parameters (if any)
on the left side of the lambda operator =>, and you put the expression
or statement block on the other side.
Note the (if any)
As Furmek mentioned, these are called expression bodied members. These are similar, but different than lambda functions.
Another way of writing this is:
public int ID { get; set; }
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am a beginner in c# and really interested in learning the language by going deeper. Recently used Lambda function to make a piece of my code but no idea how it worked.
I was mapping values from a list by writing hard code. See below:
var validRatings = new List<int> { 1, 2, 3, 4, 5 };
Used Lambda and it worked:
var validRatings = settings.grossAlphas.Select(ga => ga.fundRating).ToList();
I understand Lambda functions are anonymous but how are they different than regular functions and how do they fit in OOP context within C#?
Lambda functions are anonymous but how are they different than regular functions?
"How are X and Y different?" is in general not a good question for StackOverflow. Here, here's an apple tree and an oak tree; how are they different? Hard to say.
Briefly though:
Lambdas can be converted to delegates or expression trees. Regular functions can only be converted to delegates.
Lambdas can be expression bodied or statement bodied. Before C# 6, regular functions could only be statement bodied.
Lambdas can have their formal parameter types inferred from context; regular functions cannot.
how do they fit in OOP context within C#?
They don't. Lambdas are an idea from functional programming, not from object oriented programming. The fundamental idea of OOP is that functionality is logically connected to data; lambdas are the exact opposite of that. Lambdas are about the decoupling of functions from data objects.
If that doesn't answer your question, then ask a more clear question. What do you mean by "the oop context"?
A normal method can be called by name anytime in the code, but there are cases when we need some block of code that would be executed just once or the caller is only one, so if you see in the above code.
The main purpose of lambda expressions is to give calling code flexibility to pass it's own implementation, for example in the above case, you can have specified your own implementation and project my original collection to a new collection which contains one property named fundRating, chances are you only need this block of code for this use case, so lambda expression creates anonymous method which can only be called by the Select() method implementation.
Hope it helps!
You could create a function and name it, like so:
private string getFundRating(GrossAlpha ga)
{
return ga.fundRating;
}
And then you could pass that function in your Select. like so:
var validRatings = settings.grossAlphas.Select(getFundRating).ToList();
This would be an example of not using a lambda. In that case you are using a named function. You could use the same function somewhere else in your code or in another linq statement.
In the example you provided, you create a function on the fly, don't even name it and pass it in the Select.
Note: I assumed you had an object named GrossAlpha, and that settings.grossAlphas returns a list of those.
Regarding the other part of your question. How do they fit in the context of OOP, I can't explain it much better than Eric Lippert did.
A simple way to think of an anonymous method, albeit not a pure definition, is a method that you want to use once and move on. They're called anonymous because the aren't named methods. Lambdas, in C#, are an extremely powerful way of linking commonly used methods based on your individual objects.
What your code is doing, in one line would take many lines to write out unique methods based on every one of your classes.
To break down what your code is doing dot-by-dot:
var validRatings = settings.grossAlphas.Select(ga => ga.fundRating).ToList();
grossAlphas.Select(...): is walking through your enumeration (List, Array, etc...) object by object and aggregating them according to the parameters you supply inside the .Select(...).
ga => ga.fundRating: you are saying that you want to aggrigate ONLY the fundRating attribute from each object.
.ToList(): is making your enumeration into a List<int>().
This saves you from writing a List<int> GetFundRatings() for a single time you need to use a list of FundRatings.
Also see:
What is a lambda (function)?
C# Lambda expressions: Why should I use them?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
delegate keyword vs. lambda notation
I am using both anonymous methods and lambda expressions, but I couldn't find the difference between those expressions except syntax. Can any one please help me to find out the advantages of lambda expressions? In which scenarios would I need to use lambdas and in which would I need to go use anonymous methods?
There are subtle differences which is explained by Eric Lippert #
Lambda Expressions vs. Anonymous Methods, Part One
Lambda Expressions vs. Anonymous Methods, Part Two
Lambda Expressions vs. Anonymous Methods, Part Three
Update:
Another difference is that, Lambda expressions can be represented into Expression tress and can be parsed at runtime. While Anonymous methods can't.
They are same; in a lambda expression you can leave out the definition of your method parameters types, so it is less typing.
A lambda expression is a way to define your function in a mathematical way.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
CompilerServices.Operators equivalent on C#
I was looking for Microsoft.CSharp.CompilerServices.Operators but couldn't find it.
No there is no real equivalent to this in the C# runtime assembly.
However many these methods are essentially implementing the late bound operations for VB.Net in a declarative method (and indeed there are cases where the late binder simply just defers to these methods for operations). So these could be replicated in C# by defining methods which just explicitly defer to the C# dynamic binder.
For example, the rough equivalent of DivideObject in C# would be the following
public static dynamic DivideObject(dynamic left, dynamic right)
{
return left / right;
}