Coding man
Coding man

Reputation: 967

Should LINQ Expressions be used inside foreach loop or not?

Method 1:

var list = processQueue.Where(item => item.Priority < 6);

foreach (var item in list)
{
    Console.WriteLine("Priority : {0}, Name : {1}", item.Priority, item.Name);
}

Method 2:

foreach (var item in processQueue.Where(item => item.Priority <6))
{
    Console.WriteLine("Priority : {0}, Name : {1}", item.Priority, item.Name);
}

What is the advantage of one method over another?

Upvotes: 1

Views: 130

Answers (1)

dcastro
dcastro

Reputation: 68640

  1. Are you gonna need the list in any other place other than the loop?
  2. Does including the linq query in the loop statement make your code less readable?
  3. (As pointed out by Dan Puzey) Do you see yourself needing to inspect the contents of list while debugging?

If you answered "No" to all three questions, then go ahead and make it part of the loop.

Upvotes: 6

Related Questions