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:

//Old way
TangQuaDelegate dlg = delegate(string qua) { Console.WriteLine("Tặng quà" + qua); };
 
//Using lambda expression
TangQuaDelegate lamdaDlg = (qua) => { Console.WriteLine("Tặng quà: " + qua); }
 
//Fully syntax of lambda expression
//"=>" call go-to
(parameters) => { statement }

Here are some rules for writing lambda expressions:

//1. Có thể bỏ qua kiểu dữ liệu của parameter truyền vào
(string qua) => {Console.WriteLine("Tặng quà: " + qua);}
(qua) => {Console.WriteLine("Tặng quà: " + qua);}
 
//2. Nếu không có parameter, bỏ dấu () trống
() => {Console.WriteLine("Hello");}
 
//3. Nếu chỉ có 1 parameter, có thể bỏ luôn dấu ()
(x) => {Console.WriteLine("Hello " + x);}
x => {Console.WriteLine("Hello " + x);}
 
//4. Nếu có nhiều parameter, ngăn cách bằng dấu phẩy
(x, y) => {Console.WriteLine("Hello " + x + y);}
 
//5. Nếu anonymous function chỉ có 1 câu lệnh, có thể bỏ dấu {}
x => { Console.WriteLine("Hello " + x); }
x => Console.WriteLine("Hello " + x)
 
//6. Nếu chỉ return 1 giá trị, có thể bỏ chữ return.
//4 lambda expression sau tương đương nhau
(x) => { return x > 4; }
x => { return x > 4; }
x => return x > 4
x => x > 4

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:

var studentList = new List<Student>();
 
//This is lambda expression
var students = studentList.Where(stu => stu.Age > 20);
 
//Without it, we'd have to write something as lengthy and disgusting as the following
var student = studentList.Where(new delegate(Student stu) { return stu.Age > 20; });
 
//Or worse
public bool FindStudentWithAge(Student stu) { return stu.Age > 20; }
var student = studentList.Where(FindStudentWithAge);

Last updated