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.
- 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.
You need to login to post a comment.