Force immediate evaluation of LINQ expression using .ToArray()


/ Published in: C#
Save to your folder(s)

This shows how to immediately evaluation a LINQ query. In some cases, if it's not immediately evaluated, evaluation will be deferred (lazy, late or deferred evaluation) and repeated if the results are used in a loop or another LINQ expression.

This LINQ expression has (...).ToArray added to force immediate evaluation. Any query operator that returns a scalar value (Count) or single element (such as Single or First) forces immediate execution. Enumeration in a foreach loop will also force evaluation.

The context is a search for *.INF files under the C:\Windows (SystemRoot) directory containing search-text.


Copy this code and paste it in your HTML
  1. IEnumerable<string> windowsFiles = System.IO.Directory.GetFiles(Environment.GetEnvironmentVariable("SystemRoot"), "*.INF", System.IO.SearchOption.AllDirectories);
  2.  
  3. IEnumerable<string> files =
  4. (
  5. from f in windowsFiles
  6. where System.IO.File.ReadAllText(f).Contains(searchText)
  7. select System.IO.Path.GetFileNameWithoutExtension(f)
  8. ).ToArray(); // ToArray forces immediate evaluation.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.