0

Does the TAKE keyword used in a linq query cause the execution of that linq query to short circuit when evaluated or does that .Any method cause the short circuit?

value = (From DataRow In MyDataTable Where DataRow.Item("MyColumn").ToString = "Y" Take 1).Any
Jade L.
  • 91
  • 1
  • 8

2 Answers2

1

Both. Take will take only the first 1 record, and then the any will short circuit as soon as it finds one that matches (but there is only a maximum of 1 because of the take). You can safely remove the Take 1 and have the same performance.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57
0

The term short-circuit doesn't really apply here, because it is about boolean evaluation. See some examples here. It doesn't apply because Take doesn't return a boolean.

What you probably mean to ask is: does Take execute if Any is the next method in line? Logically, Take could be skipped if Any is also executed, because Any also stops after having found the first match.

However, we're just looking at a couple of extension methods, called consecutively:

value = MyDataTable.AsEnumerable() _
       .Where(Function(DateRow) DataRow.Item("MyColumn").ToString = "Y") _
       .(Take(1)) _
       .Any()

So Take runs, and then whatever method happens to come next, in this case Any. How would Take know it doesn't need to run? This can easily be demonstrated if you build your own extension methods from the source code and add trace statements.

Maybe an underlying question is, does it matter performance-wise? Well, it's two iterations (tops) vs. one, trying to prevent it would be a micro optimization.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291