Posted By

jimfred on 11/27/08


Tagged

Linq


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Force immediate evaluation of LINQ expression using .ToArray()


 / Published in: C#
 

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.

  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  

You need to login to post a comment.