Lambda Syntax - mcbride-clint/DeveloperCurriculum GitHub Wiki
Lambda syntax, either Lambda Expressions or Lambda Statements, are a tool to easily create anonymous functions.
The => is the lambda declaration operator.
- Expression lambda that has an expression as its body:
(input-parameters) => expression- Statement lambda that has a statement block as its body:
(input-parameters) => { <sequence-of-statements> }Most commonly seen in Linq Statements like below.
The Linq Where method is expecting a func<T, bool>.
That is a function that has one input parameter of T, in this case User, and returns a bool.
// Get User List
List<User> users = GetAllUsers();
// Narrow to Only Users with FirstName "John"
var johns = users.Where(u => u.FirstName == "John");Same as providing a method directly:
private function IsNamedJohn(User u) {
return u.FirstName == "John";
}
...
// Get User List
List<User> users = GetAllUsers();
// Narrow to Only Users with FirstName "John"
var johns = users.Where(IsNamedJohn);Lambdas can be used to create read-only properties that behave almost like parameter-less methods. Every time the property is called then the lambda will be executed again so be mindful of putting intensive operations behind lambda properties.
public class User {
public FirstName { get; set; }
public Age { get; set; }
public bool CanDrive => { return Age > 16; }
}- Microsoft Docs - Lambda Expressions - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions
- Pluralsight Course - Events, Delegates, and Lambdas - https://app.pluralsight.com/library/courses/csharp-events-delegates/table-of-contents