@BBBAEBAsCBrCrX-~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? 9P9O9S9D9; { 79$7{ 779L[] pets9z{ ?"dog"?, ?"cat"?, ?"bird"? };? 77929]with the 97 keyword. 77?97? (9L 9d ?in? pets) 77{9'9%9d); 77} 7} } ? dog cat bird? 9P9O; 9P9O.Linq9S9D9; { 79$7{? 779{An unsorted 9L 9T. 77?9L[]? letters9z{ "d", "c", "a", "b" };? 779{Use LINQ query syntax9lsort the 9T alphabetically. 77?var sorted9zfrom letter9kletters9'77 orderby letter9'77 select letter;? 779{9]with the 97 keyword. 77?97? (9L 9d ?in? sorted) 77{9'9%9d); 77} 7} } ? a b c d? 9P9O; 9 9D9; { 79AD9+<9}, 9}> _f9z9wD9+<9}, 9}>()9S79$7{? 779{Add items9ld9+. 77?_f.9n1, 2); 77_f.9n2, 3); 77_f.9n3, 4);? 779{Use var9k97 loop. 77?97? (?var? pair ?in? _f) 77{9'9%"{0},{1}", pair.Key, pair.9e); 77} 7} } ?9; version 2: C#? 9P9O; 9 9D9; { 79AD9+<9}, 9}> _h9z9wD9+<9}, 9}>()9S79$7{? 779{Add items9ld9+. 77?_h.9n5, 4); 77_h.9n4, 3); 77_h.9n2, 1);? 779{Standard 97 loop. 77?97? (?Key9ePair<9}, 9}>? pair ?in? _h) 77{9'9%"{0},{1}", pair.Key, pair.9e); 77} 7} }? 9P9O; 9 9D9; { 79$7{ 77?9u<9}>? 9t9z9w9u<9}>(); 779t.9n?1?); 779t.9n?2?); 779t.9n?3?);? 779{9]over 9t 96s 9P97-loop. 77?97? (9s969k9t) 77{9'9%96); 77}? 779{You can't r9Y 96s9ka 97-loop. 77?try 77{9'?97? (9s969k9t)9'{9'79t.?R9Y?(96);9'} 77} 77catch (9) ex) 77{9'9%ex.Message); 77} 7} } ? 1 2 3 C9, was modified; enumeration operation may not execute.? 9P9O9S9D9; { 79$7{? 779{9U of color 9Ls. 77?9L[]? colors9z{ "red", "orange", "yellow", "green" };? 779{Pr9sall colors with 9|-loop. 77?9%?":::FOR:::"?); 77?9|? (9si9z0; i < colors.L9Z; i++) 77{?9'9{Assign 9L reference based on induction variable.9'?9L 9d9zcolors[i];9'9%9d); 77}? 779{Pr9sall colors with 9oeach. 77?9%?":::FOREACH:::"?); 77?97? (var 9d9kcolors) 77{9'9%9d); 77} 7} } ? ?:::FOR:::? red orange yellow green ?:::FOREACH:::? red orange yellow green? 9P9O; 9! 9D9; { 7const 9s_max9z100000000; 79$7{ 779; program9z9w9;(); 77var s19z9-.9cNew(); 779o(9si9z0; i < _max; i++) 77{9'program.?M9[1?(); 77} 77s191; 77var s29z9-.9cNew(); 779o(9si9z0; i < _max; i++) 77{9'program.?M9[2?(); 77} 77s291; 779%(9.(s1.9" * 1000 * 1000) /9'_max).To9M("0.00 ns")); 779%(9.(s2.9" * 1000 * 1000) /9'_max).To9M("0.00 ns")); 7794.9x(); 7} 79}[] _9ds9z{ 1, 2, 3 }9S79sM9[1() 7{? 779{Access the field directly9kthe 97 expression. 77?9s9I9z0; 7797 (9s9d9k?this._9ds?) 77{9'9I += 9d; 77} 779J 9I; 7} 79sM9[2() 7{? 779{Store the field 9}o a local variable9Rthen iterate. 77?9s9I9z0; 77var 9ds9zthis._9ds; 7797 (9s9d9k?9ds?) 77{9'9I += 9d; 77} 779J 9I; 7} } ? ?3.86 ns?: 97, field ?2.26 ns?: 97, local variable?

bforeach over arrayZLINQ querySvar\List, Removebfor, foreach loops>tests foreach-loop performance