Declare query in or out of loop?
-
I need to call the same LINQ to SQL query in a foreach loop, specifying a different value in the 'where' clause each time (i.e. 'someVariable' in the example). Is it better to declare the query inside the loop or outside the loop? I have verified that I get the same results either way. Please ignore the idea of eliminating the outer loop by passing the entire key list to the query. OUTSIDE:
var someVariable = whatever;
var q = from rec in table
where rec.Key = someVariable
select rec;foreach (var key in keylist)
{
someVariable = key;
foreach (var rec in q)
{
// Do something.
}
}INSIDE:
foreach (var key in keylist)
{
var q = from rec in table
where rec.Key = key
select rec;foreach (var rec in q) { // Do something. }
}
-
I need to call the same LINQ to SQL query in a foreach loop, specifying a different value in the 'where' clause each time (i.e. 'someVariable' in the example). Is it better to declare the query inside the loop or outside the loop? I have verified that I get the same results either way. Please ignore the idea of eliminating the outer loop by passing the entire key list to the query. OUTSIDE:
var someVariable = whatever;
var q = from rec in table
where rec.Key = someVariable
select rec;foreach (var key in keylist)
{
someVariable = key;
foreach (var rec in q)
{
// Do something.
}
}INSIDE:
foreach (var key in keylist)
{
var q = from rec in table
where rec.Key = key
select rec;foreach (var rec in q) { // Do something. }
}
i think first option is better one and its working because of linq differed execution take place for more detail :- http://www.codeproject.com/tips/59614/Linq-Deferred-Execution.aspx[^]