[C# 3.0] 지연 실행

eunjin lee·2022년 10월 3일
0

C# 9.0 프로그래밍

목록 보기
33/50

LINQ 쿼리의 반환 타입이 IEnumerable, IOrderedEnumerable인 경우 lazy evaluation 또는 deferred execution 방식으로 동작한다.


💡 샘플 코드

static Func<int, bool> func; //int를 인자로 받아 bool을 반환하는 Func

static void Main(string[] args)
{
 	List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
  	func = (x) =>
            {
             Console.WriteLine("Func Executed");
             return x % 2 == 0; 
            };

	Console.WriteLine("==Where==");
	IEnumerable<int> whereList = list.Where(func);

	Console.WriteLine("==Foreach==");
	foreach(int i in whereList)
    {
    	Console.WriteLine(i);
    }
}

✅ 결과

==Where==
==Foreach==
Func Executed
Func Executed
2
Func Executed
Func Executed
4
Func Executed
Func Executed
6
Func Executed
  • Where절은 foreach문에서 열거자를 통해 요소를 순환할 때 Func 메서드를 실행한다. → lazy evaluation 또는 deferred execution)

💡 샘플 코드

static Predicate<int> pred;//int를 인자로 받아 bool을 반환하는 delegate
static void Main(string[] args)
{
	List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };


	pred = (x) =>
            {
                Console.WriteLine("Predicate Executed");
                return x % 2 == 0;
            };

	Console.WriteLine("==FindAll==");
	IEnumerable<int> findList = list.FindAll(pred);

	Console.WriteLine("==forEach==");
	foreach(int i in findList)
	{
		Console.WriteLine(i);
	}
}

✅ 결과

==FindAll==
Predicate Executed
Predicate Executed
Predicate Executed
Predicate Executed
Predicate Executed
Predicate Executed
Predicate Executed
==forEach==
2
4
6
  • FindAll은 메서드 실행 시 바로 Predicate가 실행된다.

0개의 댓글