aAbBEBAEBAsCBrCrX-~C~| 555G74VC-~C G56G74VB~~~ 6G754F6G754W~ 584G797VBZWCC G56576657}55WCZYZZZZCC-~~C 776565}8ZYBZYX

Foreach.` On a beach there are many grains of sand. Each grain is separate—it is an element in a collection. The water nearby is calm and clear.`With a foreach loop,` we evaluate each element individually. An index is not needed. With no indexes, loops are easier to write and programs are simpler.`A foreach-loop.` This is the easiest, least error-prone loop. It is preferred in many program contexts. But we lose some flexibility with it. `Index: `Foreach uses no integer index. Instead, it is used on a collection—it returns each element in order.`This is called enumeration. We eliminate errors caused by incorrect index handling.`Strings: `We use foreach, on a string array, to loop through the elements in the array.`Keywords.` Foreach is a reserved keyword. The iteration variable "string value" can be a different type. For example, we can use "int number" when looping over ints. `We must specify the keyword "in" and the object to loop over. We can use a collection or array.`LINQ.` This example uses a foreach-loop to evaluate a LINQ expression. The expression sorts an array. The LINQ extension provides queries that are evaluated lazily. `Delay: `The sorting in the example won't occur until the foreach-loop is executed.`With the LINQ extensions the foreach keyword is important. Trying to use LINQ without it is frustrating.`Var, implicit types.` The var keyword can simplify our loop syntax. Let's compare a foreach-loop with the var keyword used in the enumeration statement, with a standard foreach-loop. `Var `var`Example: `The example enumerates a Dictionary. We see how the character count in "KeyValuePair" can be reduced.`First: `The first loop uses var in the foreach loop. The var actually is of type KeyValuePair(int, int).`Second: `The second loop is the standard foreach syntax. The enumeration variable is fully specified.`List.` The foreach construct elegantly loops through list elements. But it has a drawback. It restricts any mutations made to the collection during the loop. `We use the foreach-loop construct to loop over each element in the List variable. All the integers are printed to the screen.`Restriction: `We then try calling the Remove method. This fails because of a restriction of the foreach-loop.`Removing elements.` If you want to add or remove elements during a loop, you could use a for-loop construct. But be careful to maintain correct indexes. `InvalidOperationException `invalidoperationexception`Reverse.` With the LINQ extensions, we can invoke a Reverse() method. We can then use foreach over the reversed results. This is a reversed foreach-loop of sorts. `Foreach, Reverse `foreach-reverse`For-loop.` Let's compare loops. For has more complexity in its syntax. This gives it more power if you want to modify the collection or examine adjacent elements. `Optimizing compilers analyze loop variables in for-loops. The speed of loops is critical in many programs.`In compiler theory, an expression that is based on a loop index such as "i" is called an affine expression.`Note 2: `The compiler then uses strength reduction techniques to transform slow multiplications into fast additions.`Errors.` A compile-time error is caused when we try to compile a program that incorrectly uses a foreach iteration variable. Foreach variables are read-only. `The C# compiler detects this kind of error before it ever causes a problem.`If we need to change data in a loop, a for-loop is often a better choice. With for, we can directly assign elements.`Arrays, strings.` The foreach-loop is versatile. We use it on strings, string arrays, and even DataTables. These are collections that stored as representations in memory. `Foreach: String Array `loop-string-array`Foreach: String Chars `loop-chars`Foreach: DataTable `datatable-foreach`GetEnumerator.` When designing a collection that is likely to be widely used in other code, you can implement this method. This enables the foreach-loop. `Dictionary GetEnumerator `dictionary-getenumerator`IEnumerable.` If a class implements IEnumerable, we can use the foreach-loop upon it. Many things, like Lists and arrays, implement this generic interface. `IEnumerable `ienumerable`Yield.` This feature allows the position in the control flow to be remembered and resumed when the statement finishes. It is implemented in terms of simpler constructs. `Yield `yield`Performance.` Compared to for, foreach has at best equivalent performance in typical conditions. Its benefit is not in performance but in syntax. `For, Foreach Comparison `for-foreach`Sometimes: `The foreach-loop can be used in a way that we cannot use a for-loop. It interacts with the yield keyword.`This can enhance performance—it can delay or avoid computations. But it can also reduce performance.`Benchmark.` How can we improve the iteration performance of a foreach-loop? The foreach-loop is often less efficient than a simple for-loop. `Method 1: `Uses a foreach-loop that directly accesses the instance field _values.`Method 2: `Stores the instance field into a local variable reference. Then it uses that local variable in the foreach-loop.`Result: `Because the field's address is resolved each time it is accessed, Method1() is slower. It adds indirection.`Control statements.` In the flow of control, instructions proceed in order, unless a branch transfers control to an offset. These keywords are supported in foreach-loops. `Break `break`Continue `continue`Goto `goto`Return `return`More loops.` Here are other loops we can use. For known ranges of numbers, for is best. For an infinite loop, or one with no known termination, while is ideal. `For `for`While `while`Do `do`A review.` Foreach is a powerful, concise, beautiful loop. It uses the "in" keyword and reads like a sentence. It handles arrays and works well with queries.`Loops are wonderful.` Many loops exist, but we focused on foreach. We compared it with its boring friend the "for" loop. And we caused a compile-time error.

79?263:DQbJA%Py9W@@Ph'hDQDQbJA%{PUPy{jUyp{W@@Ph'hDQ JA?-zzyq-zzb%{j-vvv{p@@'XADQ JA?-zzyq-zzb%{j-vvv{@@Xzz'XDQ JA%oznyqoznvnvnv{Wn8D@@i8pn'8{8p@@i8pnn8+')DQbJA%{SPPy{i|'|iy^{PPhy'h{iw'@hp'hDQ!JAiy%AyqAy,`wiyg3y,`wiyg3'0#O'0#O5uzhybig{p@iMy@ihphMhKMig{zViMyhyh@ihphMhKM@@ 99999 { 797{ 779[] pets9{ ?"dog"?, ?"cat"?, ?"bird"? };? 7799with the 9 keyword. 77?9? (9 9 ?in? pets) 77{ 77799); 77} 7} } ? dog cat bird? 99; 99.Linq999 { 797{? 779An unsorted 9 9. 77?9[]? letters9{ "d", "c", "a", "b" };? 779Use LINQ query syntax9sort the 9 alphabetically. 77?var sorted9from letter9letters 77777 orderby letter 77777 select letter;? 7799with the 9 keyword. 77?9? (9 9 ?in? sorted) 77{ 77799); 77} 7} } ? a b c d? 99; 9 99 { 79D9<9, 9> _f99D9<9, 9>()9797{? 779Add items9d9. 77?_f.91, 2); 77_f.92, 3); 77_f.93, 4);? 779Use var99 loop. 77?9? (?var? pair ?in? _f) 77{ 7779"{0},{1}", pair.Key, pair.9); 77} 7} } ?9 version 2: C#? 99; 9 99 { 79D9<9, 9> _h99D9<9, 9>()9797{? 779Add items9d9. 77?_h.95, 4); 77_h.94, 3); 77_h.92, 1);? 779Standard 9 loop. 77?9? (?Key9Pair<9, 9>? pair ?in? _h) 77{ 7779"{0},{1}", pair.Key, pair.9); 77} 7} }? 99; 9 99 { 797{ 77?9<9>? 9999<9>(); 779.9?1?); 779.9?2?); 779.9?3?);? 7799over 9 9s 99-loop. 77?9? (9999) 77{ 77799); 77}? 779You can't remove 9s9a 9-loop. 77?try 77{ 777?9? (9999) 777{ 77779.?Remove?(9); 777} 77} 77catch (9 ex) 77{ 7779ex.Message); 77} 7} } ? 1 2 3 C9 was modified; enumeration operation may not execute.? 99999 { 797{? 7799 of color 9s. 77?9[]? colors9{ "red", "orange", "yellow", "green" };? 779Pr9all colors with 9-loop. 77?9?":::FOR:::"?); 77?9? (9i90; i < colors.L9; i++) 77{? 7779Assign 9 reference based on induction variable. 777?9 99colors[i]; 77799); 77}? 779Pr9all colors with 9each. 77?9?":::FOREACH:::"?); 77?9? (var 99colors) 77{ 77799); 77} 7} } ? ?:::FOR:::? red orange yellow green ?:::FOREACH:::? red orange yellow green? 99; 9 99 { 7const 9_max9100000000; 797{ 779 program999(); 77var s199.9New(); 779(9i90; i < _max; i++) 77{ 777program.?M91?(); 77} 77s19; 77var s299.9New(); 779(9i90; i < _max; i++) 77{ 777program.?M92?(); 77} 77s29; 779(9(s1.9 * 1000 * 1000) / 777_max).To9("0.00 ns")); 779(9(s2.9 * 1000 * 1000) / 777_max).To9("0.00 ns")); 779.9(); 7} 79[] _9s9{ 1, 2, 3 }979M91() 7{? 779Access the field directly9the 9 expression. 77?9990; 779 (999?this._9s?) 77{ 7779 += 9; 77} 779 9; 7} 79M92() 7{? 779Store the field 9o a local variable9then iterate. 77?9990; 77var 9s9this._9s; 779 (999?9s?) 77{ 7779 += 9; 77} 779 9; 7} } ? ?3.86 ns?: 9, field ?2.26 ns?: 9, local variable?

&bZS\b>foreach over arrayLINQ queryvarList, Removefor, foreach loopstests foreach-loop performance