{"id":253,"date":"2022-01-01T16:01:59","date_gmt":"2022-01-01T09:01:59","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=253"},"modified":"2022-06-03T13:28:11","modified_gmt":"2022-06-03T06:28:11","slug":"csharp-foreach","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-foreach\/","title":{"rendered":"C# foreach"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the foreach statement to iterate over array elements.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using foreach with a single-dimensional array<\/h2>\n\n\n\n<p>To iterate over elements of a single-dimensional <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-array\/\">array<\/a>, you can use the <code><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-for-loop\/\">for<\/a><\/code> statement. However, the <code>foreach<\/code> statement provides a more simple and clean way to do so.<\/p>\n\n\n\n<p>The following uses the <code>for<\/code> statement to iterate over elements of an array:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span>&#91;] scores = { <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">4<\/span> };\n\n<span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; scores.Length; i++)\n{\n    Console.Write(<span class=\"hljs-string\">$\"<span class=\"hljs-subst\">{scores&#91;i]}<\/span> \"<\/span>);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-number\">5<\/span> <span class=\"hljs-number\">2<\/span> <span class=\"hljs-number\">1<\/span> <span class=\"hljs-number\">3<\/span> <span class=\"hljs-number\">4<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, we access the elements of the <code>scores<\/code> array using an index specified by the variable <code>i<\/code>. The variable <code>i<\/code> starts at the index of the first element (0) and ends at the index of the last element (Length &#8211; 1). In each iteration, the variable i is increased by one. Therefore, the code iterates over all the array elements.<\/p>\n\n\n\n<p>The for statement works fine but it&#8217;s quite verbose and error-prone. <\/p>\n\n\n\n<p>For example, if you don&#8217;t control the variable <code>i<\/code> properly, you&#8217;ll get an error of accessing an element at an invalid index.<\/p>\n\n\n\n<p>The following example uses the <code>foreach<\/code> statement to iterate over the elements of the <code>scores<\/code> array:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span>&#91;] scores = { <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">4<\/span> };\n\n<span class=\"hljs-keyword\">foreach<\/span> (<span class=\"hljs-keyword\">int<\/span> score <span class=\"hljs-keyword\">in<\/span> scores)\n{\n    Console.Write(<span class=\"hljs-string\">$\"<span class=\"hljs-subst\">{score}<\/span> \"<\/span>);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">5 2 1 3 4<\/code><\/span><\/pre>\n\n\n<p>In this example, the <code>foreach<\/code> statement processes the elements in the <code>scores<\/code> array in increasing index order starting from the index <code>0<\/code> and ending with the index <code>Lengh - 1<\/code>. In each iteration, the <code>foreach<\/code> statement assigns the current element to the <code>score<\/code> variable.<\/p>\n\n\n\n<p>Note that you can use the <code><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-break\/\">break<\/a><\/code> and <code><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-continue\/\">continue<\/a><\/code> statements in the <code>foreach<\/code> statement as the <code>for<\/code> statement.<\/p>\n\n\n\n<p>The <code>foreach<\/code> statement doesn&#8217;t allow you to change the array elements. For example, the following cause an error because it attempts to change the values of the array elements in a <code>foreach<\/code> loop:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">int&#91;] scores = { <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">4<\/span> };\n\n<span class=\"hljs-keyword\">foreach<\/span> (int score in scores)\n{\n    score = score * <span class=\"hljs-number\">2<\/span>; <span class=\"hljs-comment\">\/\/ error<\/span>\n    Console.Write($<span class=\"hljs-string\">\"{score} \"<\/span>);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To change the array element inside the loop, you need to use the <code>for<\/code> statement. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\">int&#91;] scores = { 5, 2, 1, 3, 4 };\n\nfor (int i = 0; i <span class=\"hljs-tag\">&lt; <span class=\"hljs-attr\">scores.Length<\/span>; <span class=\"hljs-attr\">i<\/span>++)\n{\n    <span class=\"hljs-attr\">scores<\/span>&#91;<span class=\"hljs-attr\">i<\/span>] *= <span class=\"hljs-string\">2;<\/span>\n    <span class=\"hljs-attr\">Console.Write<\/span>($\"{<span class=\"hljs-attr\">scores<\/span>&#91;<span class=\"hljs-attr\">i<\/span>]} \");\n}<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">10 4 2 6 8<\/code><\/span><\/pre>\n\n\n<p>The following table summarizes the differences between <code>foreach<\/code> and <code>for<\/code> statements:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>foreach<\/th><th>for<\/th><\/tr><\/thead><tbody><tr><td>Clean and simple<\/td><td>Complex but flexible<\/td><\/tr><tr><td>Iterate all elements<\/td><td>Iterate all or a subset of elements<\/td><\/tr><tr><td>The elements are read-only<\/td><td>The elements are changeable<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Using the foreach statement with a multidimensional array <\/h2>\n\n\n\n<p>For a <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-multidimensional-array\/\">multidimensional array<\/a>, the <code>foreach<\/code> statement increases the indices of the rightmost dimension first and then the next left dimension, and so on to the left. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span>&#91;,] matrix =\n{\n    {<span class=\"hljs-number\">1<\/span>,<span class=\"hljs-number\">2<\/span>,<span class=\"hljs-number\">3<\/span> },\n    {<span class=\"hljs-number\">4<\/span>,<span class=\"hljs-number\">5<\/span>,<span class=\"hljs-number\">6<\/span> }\n};\n\n<span class=\"hljs-keyword\">foreach<\/span>(<span class=\"hljs-keyword\">var<\/span> e <span class=\"hljs-keyword\">in<\/span> matrix)\n{\n    Console.Write(<span class=\"hljs-string\">$\"<span class=\"hljs-subst\">{e}<\/span> \"<\/span>);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-number\">1<\/span> <span class=\"hljs-number\">2<\/span> <span class=\"hljs-number\">3<\/span> <span class=\"hljs-number\">4<\/span> <span class=\"hljs-number\">5<\/span> <span class=\"hljs-number\">6<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, we have a two-dimensional array with two rows and three columns. The <code>foreach<\/code> statement iterates elements from rows 0 to 1. For each row, it iterates the elements from columns 0 to 3.<\/p>\n\n\n\n<p>If you want to control the order in which to access the array elements, you can use a nested loop with the <code>for<\/code> statement.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Use the <code>foreach<\/code> statement with one-dimensional arrays to iterate through the array elements.<\/li><li>For a multidimensional array, use the <code>for<\/code> statement to control the order in which you want to access the array elements.<\/li><\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"253\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-foreach\/\"\n\t\t\t\tdata-post-title=\"C# foreach\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"253\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-foreach\/\"\n\t\t\t\tdata-post-title=\"C# foreach\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you&#8217;ll learn how to use the foreach statement to iterate over array elements. Using foreach with a single-dimensional array To iterate over elements of a single-dimensional array, you can use the for statement. However, the foreach statement provides a more simple and clean way to do so. The following uses the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":7,"menu_order":25,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-253","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/253","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=253"}],"version-history":[{"count":4,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/253\/revisions"}],"predecessor-version":[{"id":610,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/253\/revisions\/610"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/7"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=253"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}