LAMBDA EXPRESSION in C#

Photo by Johny vino on Unsplash

1. Review the concept of Delegate

public delegate void GiveGiftDelegate(string gift);

public void GiveGift (string gift) {
Console.Write (“Gave” + gift);
}

//When using:
GiveGiftDelegate dlg = GiveGift;
// Pass the function in, not execute the function so there is no sign ()

2. Anonymous function

// Use anonmyous function, GiveGiftDlg is now a delegate
var GiveGiftDlg = function(gift) {alert ("gift"); };

function isHome(vo, GiveGift) {
var gift = "Gift received";
GiveGift(gift);
}

// Use in code
isHome (vo, GiveGiftDlg);
public delegate void GiveGiftDelegate(string gift);

GiveGiftDelegate dlg =
delegate(string gift){ Console.WriteLine("Give " + gift); };

3. Lambda expression

// Old way
GiveGiftDelegate dlg = delegate (string gift) {Console.WriteLine ("Give " + qua); };

// Use a lambda expression
GiveGiftDelegate lamdaDlg = (gift) => {Console.WriteLine ("Gift:" + gift); }

// The complete statement of lambda expression.
// The "=>" sign is called go-to
(parameters) => {statement}
Picture 2: Delegate, Anonymous method, and Lambda Expression
//1. It is possible to ignore the data type of the passed parameter
(string gift) => {Console.WriteLine ("Give gift:" + gift);}
(gift) => {Console.WriteLine ("Gift:" + gift);}

//2. If there are no parameters, leave the () blank
() => {Console.WriteLine ("Hello");}

// 3. If there is only 1 parameter, you can remove the () sign.
(x) => {Console.WriteLine ("Hello" + x);}
x => {Console.WriteLine ("Hello" + x);}

// 4. If there are many parameters, separate them with commas
(x, y) => {Console.WriteLine ("Hello" + x + y);}

// 5. If the anonymous function has only 1 statement, you can remove the {}
x => {Console.WriteLine ("Hello" + x); }
x => Console.WriteLine ("Hello" + x)

// 6. If only return 1 value, you can omit the word return.
// The following 4 lambda expressions are equivalent
(x) => {return x> 4; }
x => {return x> 4; }
x => return x> 4
x => x> 4
Picture 3: Optimize Lambda Expression

4. Lambda Expression and LINQ

Picture 4: Lambda Expression and LinQ
var studentList = new List <Student> ();

// This neat little thing is a lambda expression
var students = studentList.Where (stu => stu.Age> 20);

// If we don't have it, we have to write something that is both wordy and disgusting as follows
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);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store