방프리
21.04.20 Chapter4. LINQ 활용 (Item 32) 본문
Item 32 : Action, Predicate, Function과 순회 방식을 분리하라
익명의 델리게이트를 사용할 때는 function과 action이라는 두 가지 패턴이 있다. predicate는 시퀸스 내의 항목이
조건에 부합하는지를 bool로 반환하는 function이다.
predicate는 필터 메스드를 구현할 때 사용할 수 있다.
public static IEnumerable<T> Where<T>(
IEnumerable<T> sequence,
Predicate<T> filterFunc)
{
if (sequence == null)
throw new ArgumentNullException(nameof(sequence),
"sequence must not be null");
if (filterFunc == null)
throw new ArgumentNullException("Predicate must not be null");
foreach (T item in sequence)
if (filterFunc(item))
yield return item;
}
Func<> 델리게이트는 이터레이션 패턴과 결합하여 새로운 시퀸스를 생성할 수 있다.
public static IEnumerable<T> Select<T>(
IEnumerable<T> sequence, Func<T, T> method)
{
if (sequence == null)
throw new ArgumentNullException(nameof(sequence),
"sequence must not be null");
foreach (T element in sequence)
yield return method(element);
}
//다음과 같이 사용이 가능하다.
foreach (int i in Select(myInts, value => value * value))
WriteLine(i);
입력 타입과 출력 타입이 다른 점을 고려한다면 다음과 같이 변형도 가능하다.
public static IEnumerable<Tout> Select <T in, T out>(
IEnumerable<T in> sequence, Func<T in, T out> method)
{
foreach(var element int sequence)
yield return method(element);
}
foreach (string s in Select(myInts, value => value.ToString())
WriteLine(s);
'C# > Effective C#' 카테고리의 다른 글
21.05.29Chapter4. LINQ 활용 (Item 34) (0) | 2021.05.29 |
---|---|
21.04.24 Chapter4. LINQ 활용 (Item 33) (0) | 2021.04.24 |
21.04.15 Chapter4. LINQ 활용 (Item 31) (0) | 2021.04.16 |
21.04.03 Chapter4. LINQ 활용 (Item 30) (0) | 2021.04.03 |
21.04.02 Chapter4. LINQ 활용 (Item 29) (0) | 2021.04.02 |
Comments