Application methods and scenarios of Lambda expressions in C#

Lambda expressions provide a more concise and flexible way to define anonymous functions in C#, and provide a better coding experience in various scenarios. By using Lambda expressions, you can reduce redundant code and express the logic of functions in a more intuitive and concise manner.

When using Lambda expressions in C#, there are many application methods and application scenarios. Below I will introduce in detail the various application methods and application scenarios of Lambda expressions in C#:

  •  LINQ query

Lambda expressions are widely used in LINQ queries. They are used to define query conditions, sorting rules, and projection operations, making query logic more concise. Lambda expressions allow you to write logic directly in LINQ queries without explicitly defining anonymous functions. 

// 使用Lambda表达式进行筛选
var filtered = numbers.Where(x => x % 2 == 0);

// 使用Lambda表达式进行投影
var projected = numbers.Select(x => x * 2);

// 使用Lambda表达式进行排序
var sorted = numbers.OrderBy(x => x);
  • higher order functions 

 Lambda expressions enable C# to support higher-order functions, that is, functions that accept one or more functions as parameters or return a function. With Lambda expressions, you can easily create and pass anonymous functions, as well as perform function composition and currying operations.

// 创建高阶函数
Func<int, Func<int, int>> curriedAdd = x => y => x + y;

// 函数组合
Func<int, int> addOne = x => x + 1;
Func<int, int> multiplyByTwo = x => x * 2;
Func<int, int> composed = addOne.Compose(multiplyByTwo);

// 柯里化
Func<int, int, int> add = (x, y) => x + y;
Func<int, Func<int, int>> curriedAdd = x => y => add(x, y);
  • event handling

 Lambda expressions can be used to simplify the code for event handling. Lambda expressions allow you to define event handlers directly without explicitly writing named methods.

button.Click += (sender, e) => Console.WriteLine("Button clicked");

// 使用条件语句的Lambda表达式
button.Click += (sender, e) =>
{
    if (e.Button == MouseButton.Left)
    {
        Console.WriteLine("Left button clicked");
    }
    else if (e.Button == MouseButton.Right)
    {
        Console.WriteLine("Right button clicked");
    }
};
  • parallel programming

Lambda expressions can be used in tasks and parallel loops in parallel programming. With Lambda expressions, you can define parallel tasks and loop bodies in a more concise way. 

// 并行任务
Task.Run(() => DoSomethingAsync());

// 并行循环
Parallel.For(0, 10, i => Console.WriteLine(i));

Parallel.ForEach(numbers, n => Console.WriteLine(n));
  •  delegates and events

Lambda expressions can be used as instances of delegate types to be passed to other methods or used in events. 

Action<int> printNumber = x => Console.WriteLine(x);

Func<int, int, int> sum = (x, y) => x + y;

EventHandler clickHandler = (sender, e) => Console.WriteLine("Clicked");

  •  Asynchronous lambdas

In C#, asynchronous lambda expressions can asyncbe used with asynchronous methods (methods decorated with keywords) to execute corresponding logic in asynchronous operations. By asyncusing modifiers with Lambda expressions, you can use asynchronous operations, asynchronous await, and asynchronous returns in expressions. 

// 异步Lambda表达式示例
Func<int, Task<int>> asyncAdd = async x =>
{
    await Task.Delay(1000);  // 模拟异步操作
    return x + 1;
};

// 在异步方法中调用异步Lambda表达式
async Task RunAsyncLambda()
{
    int result = await asyncAdd(2);
    Console.WriteLine(result);
}

// 调用异步方法
RunAsyncLambda().Wait();

Asynchronous Lambda expressions are often used in scenarios that need to execute logic in an asynchronous context, such as using asynchronous LINQ queries, asynchronous event processing, asynchronous tasks, and asynchronous loops. By using asynchronous Lambda expressions, you can more easily write and manage asynchronous operations, and process the results of asynchronous code. 

------------------------------ 

Starting with C# 10, lambda expressions may have natural types. The compiler does not force you to declare a delegate type (such as Func<...> or Action<...>) for the Lambda expression, but infers the delegate type from the Lambda expression 

// 自然类型的Lambda表达式示例
int[] numbers = { 1, 2, 3, 4, 5 };

// 无需显式声明委托类型
var evenNumbers = numbers.Where(n => n % 2 == 0);

// 输出结果
foreach (var number in evenNumbers)
{
    Console.WriteLine(number);
}

Here are some examples of using Lambda expressions in C#: 

// 使用Lambda表达式定义一个简单的加法函数
Func<int, int, int> add = (x, y) => x + y;

// 调用Lambda函数
int result = add(2, 3);
Console.WriteLine(result);  // 输出:5

// 将Lambda表达式作为参数传递给高阶函数
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> squared = numbers.Select(x => x * x).ToList();
Console.WriteLine(string.Join(", ", squared));  // 输出:1, 4, 9, 16, 25

 

Guess you like

Origin blog.csdn.net/book_dw5189/article/details/131504578