Return to Snippet

Revision: 9878
at November 27, 2008 11:54 by jimfred


Initial Code
IEnumerable<string> windowsFiles = System.IO.Directory.GetFiles(Environment.GetEnvironmentVariable("SystemRoot"), "*.INF", System.IO.SearchOption.AllDirectories);

IEnumerable<string> files = 
(
  from f in windowsFiles
  where System.IO.File.ReadAllText(f).Contains(searchText)
  select System.IO.Path.GetFileNameWithoutExtension(f)
).ToArray(); // ToArray forces immediate evaluation.

Initial URL


Initial Description
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.

Initial Title
Force immediate evaluation of LINQ expression using .ToArray()

Initial Tags


Initial Language
C#