C# 中的 Lambda 表达式
发布: (2026年2月22日 GMT+8 04:25)
4 分钟阅读
原文: Dev.to
Source: Dev.to
Introduction
在 C# 中,lambda 表达式允许以简短且可读的方式编写匿名(未命名)方法。它们使用 =>(lambda 运算符)定义。lambda 表达式在 LINQ 查询、事件订阅以及函数式编程风格中尤为常见。
Syntax
lambda 表达式由参数列表和主体组成。对于简单表达式,不需要大括号;使用多行主体时,可以写大括号和 return。
// Single parameter, single‑line expression
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // 25
// Lambda with multiple parameters
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // 7
// Multi‑line lambda
Func<int, int, int> multiply = (a, b) =>
{
Console.WriteLine($"Multiplying: {a} * {b}");
return a * b;
};
Console.WriteLine(multiply(2, 6)); // 12
Using Action and Func
Action– 表示不返回值的方法。Func– 表示返回结果的方法。
Action greet = () => Console.WriteLine("Hello!");
greet(); // Hello!
Func<string, int> length = s => s.Length;
Console.WriteLine(length("Lambda")); // 6
Lambda Expressions in LINQ
lambda 让过滤、排序和投影集合变得轻而易举。
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
// Filter even numbers
var evens = numbers.Where(x => x % 2 == 0);
Console.WriteLine(string.Join(", ", evens)); // 2, 4, 6
// Calculate squares
var squares = numbers.Select(x => x * x);
Console.WriteLine(string.Join(", ", squares)); // 1, 4, 9, 16, 25, 36
Event Handling with Lambdas
lambda 提供了一种简洁的方式来订阅事件,而无需定义单独的方法。
public class Button
{
public event EventHandler? Click;
public void SimulateClick()
{
Console.WriteLine("Button clicked!");
Click?.Invoke(this, EventArgs.Empty);
}
}
class Program
{
static void Main()
{
var btn = new Button();
// Capture event with a lambda
btn.Click += (s, e) => Console.WriteLine("Event: Button was clicked.");
btn.SimulateClick();
}
}
Closures
lambda 可以捕获其定义作用域中的变量,形成 闭包。
int counter = 0;
Action increment = () =>
{
counter++;
Console.WriteLine($"Counter: {counter}");
};
increment(); // Counter: 1
increment(); // Counter: 2
Real‑World Example: Filtering Products
public class Product
{
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
class Program
{
static void Main()
{
var products = new List
{
new Product { Name = "Laptop", Price = 25000m },
new Product { Name = "Mouse", Price = 300m },
new Product { Name = "Keyboard", Price = 600m },
new Product { Name = "Monitor", Price = 4500m }
};
// Find products above 1000
var expensiveProducts = products.Where(p => p.Price > 1000);
foreach (var p in expensiveProducts)
{
Console.WriteLine($"{p.Name} - {p.Price} USD");
}
// Calculate average price
var avg = products.Average(p => p.Price);
Console.WriteLine($"Average price: {avg:0.00} USD");
}
}
Summary
- 使用
=>运算符定义简短的匿名方法。 - 常与
Action和Func一起使用。 - 在 LINQ 中用于过滤、选择和排序,必不可少。
- 用于事件订阅时可省去额外的样板代码。
- 支持闭包,能够访问外部变量。