Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't a method execute from within LINQ Where method

Tags:

c#

linq

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?

like image 827
Pricey Avatar asked Jan 10 '16 23:01

Pricey


2 Answers

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();
like image 163
Sam Avatar answered Nov 20 '22 10:11

Sam


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();
like image 3
Yacoub Massad Avatar answered Nov 20 '22 09:11

Yacoub Massad