방프리

21.04.20 Chapter4. LINQ 활용 (Item 32) 본문

C#/Effective C#

21.04.20 Chapter4. LINQ 활용 (Item 32)

방프리 2021. 4. 20. 22:20

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);

 

Comments