C# lambda表达式的几个案例

2024-10-18


转自知乎 罗泽南


Lambda 表达式在 C# 中用于简化匿名方法的书写形式。它广泛用于 LINQ 查询、事件处理、委托等场景。下面通过几个详细的案例展示 lambda 表达式的各种用法。

案例 1:基本的 Lambda 表达式

最基本的 Lambda 表达式通常是用于表示一个简单的函数或委托。在下面的例子中,我们定义了一个委托 Func<int, int>,并使用 Lambda 表达式为它赋值。

using System;

class Program{
    static void Main()
    {
        // Lambda 表达式:接收一个参数 x,返回 x 的平方        
        Func<int, int> square = x => x * 2;
        
        int result = square(5); // 计算 5 的平方        
        Console.WriteLine(result); // 输出 10    
    }
}

解释:

案例 2:Lambda 表达式和 LINQ

Lambda 表达式在 LINQ 查询中非常常见。下面的例子展示如何使用 Lambda 表达式过滤并操作集合中的数据。

using System;using 
System.Collections.Generic;using 
System.Linq;

class Program{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        // 使用 Lambda 表达式来筛选出所有的偶数        
        IEnumerable<int> evenNumbers = numbers.Where(x => x % 2 == 0);
        Console.WriteLine("Even numbers:");
        foreach (var number in evenNumbers)
        {
            Console.WriteLine(number); // 输出 2, 4, 6, 8, 10        
        }
    }
}

解释:

案例 3:Lambda 表达式和事件处理

Lambda 表达式也可以用作事件处理器的简写形式。通常在添加事件处理器时可以使用匿名方法或 Lambda 表达式。

using System;

class Program{
    static void Main()
    {
        // 使用 Lambda 表达式来处理按钮点击事件        
        Button button = new Button();
        button.Click += (sender, e) => Console.WriteLine("Button clicked!");
        
        // 模拟按钮点击        
        button.OnClick();
    }
}

class Button{
    public event EventHandler Click;
    public void OnClick()
    {
        // 触发事件        
        Click?.Invoke(this, EventArgs.Empty);
    }
}

解释:

案例 4:复杂的 Lambda 表达式(多参数、多行)

Lambda 表达式不仅可以用于简单的表达式,它还支持多参数和多行代码。我们可以使用花括号 {} 来定义多行 Lambda 表达式。

using System;

class Program{
    static void Main()
    {
        // 定义一个接受两个参数的 Lambda 表达式,并包含多行代码        
        Func<int, int, int> addAndMultiply = (x, y) =>
        {
            int sum = x + y;
            return sum * 2; // 返回和的两倍        
        };
        int result = addAndMultiply(3, 4);
        Console.WriteLine(result); // 输出 14    
    }
}

解释:

案例 5:Lambda 表达式与 Action 和 Predicate

using System;using 
System.Collections.Generic;

class Program{
    static void Main()
    {
        // 使用 Action Lambda 表达式来输出消息        
        Action<string> greet = message => Console.WriteLine(message);
        greet("Hello, World!"); // 输出 Hello, World!
        // 使用 Predicate Lambda 表达式来检查数字是否为正        
        Predicate<int> isPositive = x => x > 0;
        List<int> numbers = new List<int> { -1, 2, -3, 4, 5 };
        List<int> positiveNumbers = numbers.FindAll(isPositive);
        Console.WriteLine("Positive numbers:");
        foreach (var number in positiveNumbers)
        {
            Console.WriteLine(number); // 输出 2, 4, 5        
        }
    }
}

解释:

案例 6:Lambda 表达式与表达式树

表达式树用于将 Lambda 表达式转换为数据结构,可以在运行时分析和修改。这个功能主要用于动态 LINQ 查询。

using System;
using System.Linq.Expressions;

class Program{
    static void Main()
    {
        // 创建一个 Lambda 表达式的表达式树        
        Expression<Func<int, int>> expression = x => x * x;
        
        // 编译并执行表达式        
        Func<int, int> square = expression.Compile();
        Console.WriteLine(square(5)); // 输出 25    
    }
}

解释:

总结

这些案例展示了 Lambda 表达式在不同场景中的使用方式,让代码更简洁、直观。


返回
;