1

I have the following loop:

foreach (var key in model.AllKeys.Where(k => !k.StartsWith("hdn") && !k.StartsWith("__"))) 
{ 
  var field = form.Fields.Where(f => f.Key.Equals(key));
  formFields.Add(key, model[key]); 
}

I was just wondering if the where in model.AllKeys.Where(k => !k.StartsWith("hdn") && !k.StartsWith("__")) is run once or for each item in the loop as when you step over the code it hits it each time in the loop.

Would it be better to do this:

var keys = model.AllKeys.Where(k => !k.StartsWith("hdn") && !k.StartsWith("__"))
foreach (var key in keys) 
{ 
  var field = form.Fields.Where(f => f.Key.Equals(key));
  formFields.Add(key, model[key]); 
}
Pete
  • 57,112
  • 28
  • 117
  • 166
  • `Where` is executed once but the inner predicate is evaluated for every item in the source collection `model.AllKeys`. – Lee Aug 31 '17 at 15:41
  • 2
    It would execute the same way. – Matt Rowland Aug 31 '17 at 15:41
  • Both should be same – ssilas777 Aug 31 '17 at 15:42
  • Ah ok, that's good to know thanks – Pete Aug 31 '17 at 15:43
  • 1
    You could use a Join to combine the filtered `AllKeys` with the `form.Fields` and iterate only once over the results. This would be cleaner and allow you to optimize each collection separately, eg by changing them into hashsets or dictionaries. You could avoid `formFields.Add` too and convert the results of the single query into a dictionary with `ToDictionary()` – Panagiotis Kanavos Aug 31 '17 at 15:46

0 Answers0