In a console app, from a static method in main class Program, I am calling:
internal class Module
{
public bool EnsureModuleLocalInstall()
{
if (CheckModuleUpToDateLocal())
return true;
else if (DownloadComponentData())
if(InstallModuleLocal())
return true;
return false;
}
}
var availableModules = new List<Module>();
... // Add several 'Modules' to list
var installed = availableModules.Where(m => m.EnsureModuleLocalInstall());
I have both set a break-point, and also checked the expected outcome (module installed locally), but from all indications the method 'EnsureModuleLocalInstall' is not being executed.
Am I missing something obvious, or am I expecting too much from the LINQ 'Where' method and should use a LINQ ForEach?
The Where
method is implemented using deferred execution, so the query won't actually be run until you iterate over the result. The simplest way to get your list of installed modules is to call ToList
on the query return value:
var installed = availableModules.Where(m => m.EnsureModuleLocalInstall()).ToList();
Most LINQ methods (like the Where
method) will return to you an implementation of IEnumerable<T>
that does not contain the result of the query but instead contains all the information necessary to execute the query. The query is only executed when you start enumerating the IEnumerable<T>
. This is called Deferred Execution.
One way to enumerate the IEnumerable<T>
is to invoke ToList
like this:
var installed = availableModules.Where(m => m.EnsureModuleLocalInstall()).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With