Clone
1
3_linq_queries
jason.zhu edited this page 2021-05-11 10:29:35 +10:00
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:

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. Lets 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:

  1. Fetch all 1000 products (Using loop with IEnumerable)
  2. Calculate the price of all 1000 products
  3. Order 1000 prices
  4. Convert all the prices to dollars
  5. Take the top 5 of those prices

Because of deferred execution however, this can be reduced to:

  1. Fetch 10 products
  2. Calculate the price of 10 products
  3. Order 10 prices
  4. Convert 5 of these prices to dollars