Page:
3_linq_queries
Clone
This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
LINQ Queries
Creating a Custom Filter Operator & Creating an Operator with Yield Return
Reference:
- Must Read: yield (C# Reference)
- Must Read: Deferred Execution vs Immediate Execution in LINQ
- Must Read: Yield return in C#
yield
contextual keyword make return
deferred
By using deferred execution we can make some methods simpler, some faster and some even possible where they were impossible before (remember the infinite number generator). The entire LINQ part of C# is built around deferred execution. Let’s see a few sample how deferred execution can make things more efficient
var dollarPrices = FetchProducts().Take(10)
.Select(p => p.CalculatePrice())
.OrderBy(price => price)
.Take(5)
.Select(price => ConvertTo$(price));
Suppose we have 1000 products. If the above method did not have deferred execution, it would mean we would:
- Fetch all 1000 products (Using loop with
IEnumerable
) - Calculate the price of all 1000 products
- Order 1000 prices
- Convert all the prices to dollars
- Take the top 5 of those prices
Because of deferred execution however, this can be reduced to:
- Fetch 10 products
- Calculate the price of 10 products
- Order 10 prices
- Convert 5 of these prices to dollars