Why the LINQ Where method will not execute

In a console application from a static method in the main class program, I call:

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 set a breakpoint and also checked the expected result (the module is installed locally), but the "EnsureModuleLocalInstall" method does not execute from all the instructions.

Am I missing something obvious or am expecting too much of the LINQ Where method and should I use LINQ ForEach?

+5
source share
2 answers

The Where method is implemented using deferred execution , so the query will not actually be executed until you get to the result. The easiest way to get a list of installed modules is to call ToList in the return value of the request:

 var installed = availableModules.Where(m => m.EnsureModuleLocalInstall()).ToList(); 
+3
source

Most LINQ methods (such as the Where method) will return an IEnumerable<T> implementation that does not contain the result of the query, but instead contains all the information needed to complete the query. The request is only executed when the IEnumerable<T> enumeration is started. This is called deferred execution.

One way to list IEnumerable<T> is to call ToList as follows:

 var installed = availableModules.Where(m => m.EnsureModuleLocalInstall()).ToList(); 
+3
source

Source: https://habr.com/ru/post/1240295/


All Articles