0

I'm a little unsure of deferred execution in the following scenario. How often is the IEnumerable Linq expression evaluated in the following fragment? Would I be better off assigning it to a local variable before the foreach loop?

foreach (var x in y.Where(s => s.Length > 0))
{
   // do something
}

// where y is, for example, an IEnumerable<string>
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
haughtonomous
  • 4,602
  • 11
  • 34
  • 52
  • `foreach()` is syntactic sugar, it obtains the enumerator and operates on that. Please try searching before asking a new question. – CodeCaster Jun 26 '18 at 10:08
  • Please have a look at https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/language-specification/statements#the-foreach-statement, in particular which gives the expanded version of `foreach (V v in x) embedded_statement`. Does this help answer your question? – Micha Wiedenmann Jun 26 '18 at 10:09
  • 1
    @CodeCaster Calling `foreach` a synctactic sugar is a little overboard. What it does is quite complex and long... Too much long to call it simply synctactic sugar (but you are technically correct... only with your definition we could cut away 90% of the C# language as synctactic sugar probably) – xanatos Jun 26 '18 at 10:10
  • Codecaster, those questions weren't suggested as possible duplicates, by the way. – haughtonomous Jun 26 '18 at 11:31

0 Answers0