C#의 람다 식
Source: Dev.to
소개
C#에서 람다 식은 익명(이름 없는) 메서드를 짧고 가독성 있게 작성할 수 있게 해줍니다. =>(람다 연산자)를 사용해 정의합니다. 람다 식은 특히 LINQ 쿼리, 이벤트 구독, 함수형 프로그래밍 스타일에서 많이 사용됩니다.
구문
람다 식은 매개변수 목록과 본문으로 구성됩니다. 간단한 식에서는 중괄호가 필요 없으며, 여러 줄 본문을 사용할 경우 중괄호와 return을 쓸 수 있습니다.
// 단일 매개변수, 한 줄 식
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // 25
// 여러 매개변수 람다
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // 7
// 여러 줄 람다
Func<int, int, int> multiply = (a, b) =>
{
Console.WriteLine($"Multiplying: {a} * {b}");
return a * b;
};
Console.WriteLine(multiply(2, 6)); // 12
Action과 Func 사용하기
Action– 반환값이 없는 메서드를 나타냅니다.Func– 결과를 반환하는 메서드를 나타냅니다.
Action greet = () => Console.WriteLine("Hello!");
greet(); // Hello!
Func<string, int> length = s => s.Length;
Console.WriteLine(length("Lambda")); // 6
LINQ에서의 람다 식
람다를 사용하면 컬렉션을 필터링하고, 정렬하고, 투영하는 것이 쉬워집니다.
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
// 짝수만 필터링
var evens = numbers.Where(x => x % 2 == 0);
Console.WriteLine(string.Join(", ", evens)); // 2, 4, 6
// 제곱값 계산
var squares = numbers.Select(x => x * x);
Console.WriteLine(string.Join(", ", squares)); // 1, 4, 9, 16, 25, 36
람다를 이용한 이벤트 처리
람다를 사용하면 별도의 메서드를 정의하지 않고도 이벤트를 간결하게 구독할 수 있습니다.
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();
// 람다로 이벤트 캡처
btn.Click += (s, e) => Console.WriteLine("Event: Button was clicked.");
btn.SimulateClick();
}
}
클로저
람다 식은 정의된 스코프의 변수를 캡처하여 클로저를 형성할 수 있습니다.
int counter = 0;
Action increment = () =>
{
counter++;
Console.WriteLine($"Counter: {counter}");
};
increment(); // Counter: 1
increment(); // Counter: 2
실전 예제: 제품 필터링
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 }
};
// 가격이 1000 이상인 제품 찾기
var expensiveProducts = products.Where(p => p.Price > 1000);
foreach (var p in expensiveProducts)
{
Console.WriteLine($"{p.Name} - {p.Price} USD");
}
// 평균 가격 계산
var avg = products.Average(p => p.Price);
Console.WriteLine($"Average price: {avg:0.00} USD");
}
}
요약
- 짧은 익명 메서드는
=>연산자를 사용해 정의합니다. Action과Func와 함께 자주 사용됩니다.- LINQ에서 필터링, 선택, 정렬 등에 필수적입니다.
- 별도 보일러플레이트 없이 이벤트 구독에 유용합니다.
- 클로저를 지원해 외부 변수에 접근할 수 있습니다.