user2191213
user2191213

Reputation: 61

LINQ, Lambda, confused

Can anybody explain why I don't see the (my) expected output for the WriteLine? I can see it when I'm debugging it in VS and refresh the 'result' to see its content in my Local window inside VS. THX

Func<Category, bool> del = (Category cat) => { 
    System.Console.WriteLine(cat.CategoryName);
    return cat.CategoryID > 1; 
};


NorthwindEntities nw = new NorthwindEntities();

var result = nw.Categories.Where<Category>(del);

Console.Read();

Upvotes: 0

Views: 103

Answers (4)

JLRishe
JLRishe

Reputation: 101662

LINQ structures are lazy-evaluated, which means that your lambda function will not be invoked until items are requested from the enumeration (and even then, not necessarily all at once). This should cause the values to be output to the console:

var result = nw.Categories.Where<Category>(del).ToList();

Please note the implications here: if you did this, the values would be output to the console twice:

var result = nw.Categories.Where<Category>(del);
var otherVariable = result.ToList();
foreach(var item in result)
{
   // do something
}

This is a good reason why you should avoid involving code with side-effects in your LINQ queries.

Upvotes: 5

LukeHennerley
LukeHennerley

Reputation: 6434

This is due to lazy evaluation. The function hasn't actually been executed yet, so it isn't enumerated until you either enumerate it yourself or you do something like this:

Category[] categories = nw.Categories.Where<Category>(del).ToArray();

Calling this will invoke the evaluation. You can read up about this on the web but here is an article to kick things off.

Upvotes: 0

Alex Tsvetkov
Alex Tsvetkov

Reputation: 1659

Perhaps you need to materialize the query. You result is an IEnumerable, so the delegate will file only when the result is actually enumerated.

Try this: var result = nw.Categories.Where<Category>(del).ToList();

Upvotes: 1

Sean
Sean

Reputation: 62472

You need to do something with results in order for your lambda to exeucute. Try this:

var result = nw.Categories.Where<Category>(del);
foreach(var r in result)
{
}

As you enumerate over result your lambda will be called.

Upvotes: 1

Related Questions