📜  c# lambdas - C# (1)

📅  最后修改于: 2023-12-03 14:59:40.218000             🧑  作者: Mango

C# Lambdas

Lambdas are anonymous functions that can be defined inline in C#. They are useful when you want to pass a piece of code as a parameter to a method. In this article, we will explore C# Lambdas in detail.

Syntax

The syntax for a Lambda expression is as follows:

(parameters) => expression

The => is called the Lambda operator or arrow operator. The parameters can be zero or more and the expression can be a single statement or a block of statements enclosed in curly braces.

Here's an example of a Lambda expression that takes a string parameter and returns the length of the string:

(string s) => s.Length;
Using Lambdas

Lambdas are commonly used with higher-order functions such as the Where and Select methods of the System.Linq namespace. These methods take Lambda expressions as parameters.

Here's an example of using a Lambda expression with the Where method to filter a list of integers:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var result = numbers.Where(n => n % 2 == 0);

This code creates a list of integers and filters out the odd numbers using a Lambda expression.

Capturing Variables

Lambda expressions can capture variables from the enclosing scope. This means that the Lambda expression can access and modify variables declared in the same method, as well as any instance or static variables of the enclosing class.

Here's an example of using a Lambda expression to capture a variable from the enclosing scope:

int factor = 2;
Func<int, int> multiplyByFactor = (int n) => n * factor;
int result = multiplyByFactor(5); // returns 10

In this code, we define a Lambda expression that multiplies a number by a factor. The factor variable is captured from the enclosing scope.

Conclusion

In this article, we've explored the syntax and usage of C# Lambdas. They are a powerful tool for writing concise and expressive code. By using Lambdas with higher-order functions, we can write code that is both efficient and easy to read.