Lambda Expression

As mentioned in the previous article, a delegate is a data type that points to a function, so when assigning value to a delegate, we must assign a function, as in the example below:

public delegate void TangQuaDelegate(string qua);
 
public void tangQua(string qua) {
   Console.Write("Da tang " + qua);
}

TangQuaDelegate dlg = tangQua;

Anonymous function

So, every time we want to pass a function to the delegate, we have to define that function, quite annoying, right? In javascript, there is an anonymous method, write the function directly without defining as follows:

var tangQuaDlg = function(qua) { alert("qua"); };
 
function oNha(vo, tangQua){
   var qua = "Quà đã nhận";
   tangQua(qua);
}
 
oNha(vo, tangQuaDlg);

Luckily, in C#, we can also write anonymous functions in the following way (Since .NET 2.0):

public delegate void TangQuaDelegate(string qua);
 
TangQuaDelegate dlg =
          delegate(string qua) { Console.WriteLine("Tang quà" + qua); };

We find that writing delegates this way is quite cumbersome, right? Microsoft saw that too, and they added lambda expressions and .NET 3.0. If you want to know what a lambda expression is, see below.

3. Lambda expression

I want to repeat a story for the nth time: "The developers at Microsoft are very lazy, so they added many things to C#.NET, making C#.NET developers lazy." We can understand a lambda expression as a more concise way of writing an anonymous function:

Here are some rules for writing lambda expressions:

At this point, some of you will exclaim in surprise: "Ah, that's it." This is how we apply the above steps to shorten a lambda expression.

Some of you will also wonder: Oh, I thought a lambda expression was something terrible, but it turns out it's that simple. Yes, because it is so simple, many people use it without knowing its name or exactly what it is .

Lambda Expression and LINQ

Have you ever seen what the param passed to a LINQ function like Where, First is?. Yes, it is a delegate for a function whose return type is bool (See more about Func in the previous article)

Therefore, we use a lambda expression to pass an anonymous function to the Where or First function . For example, when using the LINQ Where function to find elements in an array:

Last updated