less than 1 minute read

c# 람다식(Lambda Expression)

람다 식 연산자( => )를 이용하여 익명(이름을 명시하지 않은)함수를 만들고, 전달할 수 있다.

식(expression)을 지정한 식 람다

(input-parameters) => expression

문(sequence)으로 지정한 문 람다

(input-parameters) => { <sequence-of-statements> }

람다 식을 만드려면 좌변에 매개변수(input-parameters)를 지정하고, 우변에 식 또는 중괄호에 둘러쌓인 문을 지정한다. 우변이 식인 식 람다의 경우, 식의 결과값이 리턴값으로 간주된다.

람다 식은 대리자(delegate) 형식으로 변환 가능하다.

Func<int, int> square = x => x * x;
Console.WriteLine(square(5));
// Output:
// 25

람다 식 활용 예시

Function이나 Delegate를 전달해야 하는 상황에서 람다 식은 매우 유용하다.

ForEach() 의 인자로 전달

List<int> sampleList = new List<int>{0, 9, 2, 6, 3, 5, 7, 4, 8, 1 };

int sum = 0;
sampleList.ForEach(item => sum+=item); // 식 람다 사용
Console.WriteLine($"리스트의 합계는 {sum} 입니다."); // 45

List.Sort()의 인자로 전달

List<int> sampleList = new List<int>{0, 9, 2, 6, 3, 5, 7, 4, 8, 1 };

int sum = 0;
sampleList.Sort((itemA, itemB) => itemA.CompareTo(itemB));// 람다식으로 전달한 delegate
sampleList.ForEach(item => Console.WriteLine(item));

두 경우에서, delegate를 선언하여 인자로 넣는 과정이 람다식 하나로 해결된다. 이 외에도 callBack이나 event 처리 등 재사용되지않는 익명함수 전달이 필요한 부분에서 편리하게 사용할 수 있다.