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
💡 샘플 코드
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