English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C#3.0 (.NET 3.5)Introduces lambda expressions and LINQ. Lambda expressions are a shorter way to represent anonymouse methods using some special syntax.
For example, the following anonymouse method is used to check if a student is a teenager:
delegate(Student s) { return s.Age >} 12 && s.Age < 20; };
Dim isStudentTeenAger = Function(s As Student) As Boolean Return s.Age > 12 And s.Age < 20 End Function
You can represent the above anonymous methods using Lambda expressions in C# and VB.Net as follows:
s => s.Age > 12 && s.Age < 20
Function(s) s.Age > 12 And s.Age < 20
Let's see how lambda expressions evolve from the following anonymous method.
delegate(Student s) { return s.Age >} 12 && s.Age < 20; };
Lambda expressions are evolved from anonymous methods by first deleting the delegate keyword and parameter type and adding the lambda operator =>
The above lambda expression is absolutely valid, but if there is only one return statement, it is not necessary to use braces, return, and semicolon. Therefore, we can delete it.
In addition, if there is only one parameter, the parentheses () can be deleted.
Therefore, we get the lambda expression: s => s.Age > 12 && s.Age < 20 WheresIt is the parameter,=>It is the lambda operator,s.Age > 12 && s.Age < 20It is the expression body:
The way we obtain lambda expressions in VB.Net can be written as follows:
The calling method of a lambda expression is the same as that of a delegate using ()
Note: VB.Net does not support the lambda operator =>
If you need to pass multiple parameters, you can enclose the parameters in parentheses, as shown below:
Example: Specifying multiple parameters in Lambda expressions in C#
(s, youngAge) => s.Age >= youngage;
If the parameter expression is not clear, you can also specify the type of each parameter:
(Student s, int youngAge) => s.Age >= youngage;Example: Specifying multiple parameters in Lambda expressions in VB.Net
Function(s, youngAge) s.Age >= youngAge
Lambda expressions do not necessarily need to have at least one parameter. Lambda expressions can also be specified without any parameters.
() => Console.WriteLine("Parameterless lambda expression")
If you want to include multiple statements in the body, enclose the expression in curly braces:
(s, youngAge) =>{ Console.WriteLine("Lambda expressions containing multiple statements in the body"); Return s.Age >= youngAge;}
Function(s, youngAge) Console.WriteLine("Lambda expressions containing multiple statements in the body") Return s.Age >= youngAge End Function
You can declare a variable in the expression body to use it anywhere in the expression body, as shown below:
s => { int youngAge = 18; Console.WriteLine("Lambda expressions containing multiple statements in the body"); return s.Age >= youngAge; }
Function(s) Dim youngAge As Integer = 18 Console.WriteLine("Lambda expressions containing multiple statements in the body") Return s.Age >= youngAge End Function
Lambda expressions can also be assigned to built-in delegates such as Func, Action, and Predicate.
Lambda expressions can be assigned to the Func<in T, out TResult> delegate type. The last parameter type in the Func delegate is the return type, and the rest are input parameters.Visit the Func delegate section of the C# tutorial for more information.
Consider the following lambda expression to understand if a student is a teenager.
Func<Student, bool> isStudentTeenAger = s => s.age > 12 && s.age < 20; Student std = new Student() { age = 21 }; bool isTeen = isStudentTeenAger(std);// Return false
Dim isStudentTeenAger As Func(Of Student, Boolean) = Function(s) s.Age > 12 And s.Age < 20 Dim stud As New Student With {.Age = 21} Dim isTeen As Boolean = isStudentTeenAger(stud) // Returns false
In the above example, the Func delegate expects the first input parameter to be of type Student and the return type to be a boolean value. The lambda expression s => s.age > 12 && s.age < 20 meets the Func<Student, bool> delegate requirements, as shown below:
The Func <> delegate shown above will become a function as follows.
bool isStudentTeenAger(Student s) { return s.Age > 12 && s.Age < 20; }
Unlike the Func delegate,Action DelegateCan only have input parameters. Use the Action delegate type when you do not need to return any value from the lambda expression.
Action<Student> PrintStudentDetail = s => Console.WriteLine("Name: {0}, Age: {1} Student std = new Student() { StudentName = "Bill", Age =21}; PrintStudentDetail(std);//Output: Name: Bill, Age: 21
Dim printStudentDetail As Action(Of Student) = Sub(s) Console.WriteLine("Name: {0}, Age: {1} Dim stud As New Student With {.StudentName = "Bill", .Age = 21} printStudentDetail(stud)//Output: Name: Bill, Age: 21
Generally, lambda expressions are used together with LINQ queries. The enumerable static class includes the extension methods IEnumerable<T> where it accepts Func<TSource, bool>. Therefore, the collected Where() extension method IEnumerable<Student> needs to be passed through Func<Student, bool> as shown below:
Therefore, now, you can pass the lambda expression assigned to the Func delegate to the extension method Where() as follows using method syntax:
IList<Student> studentList = new List<Student>(){...}; Func<Student, bool> isStudentTeenAger = s => s.age > 12 && s.age < 20; var teenStudents = studentList.Where(isStudentTeenAger).ToList<Student>();
IList<Student> studentList = new List<Student>(){...}; Func<Student, bool> isStudentTeenAger = s => s.age > 12 && s.age < 20; var teenStudents = from s in studentList where isStudentTeenAger(s) select s;
You can pass the Func delegate in the same way in VB.Net.
Lambda expressions are a shorthand method for representing anonymous methods.
Lambda Expression Syntax: Parameter => Expression Body
Lambda expressions can have zero parameters.
The parentheses () of the Lambda expression can contain multiple parameters.
Lambda expressions can contain multiple statements in the body expression within the curly braces {}.
Lambda expressions can be assigned to Func, Action, or Predicate delegates.
Lambda Expression can be called in a way similar to delegates.