C# foreach loop

foreach() loop iterates through all key and value pairs of a dictionary.

using System.Collections.Generic;
using System.Windows.Forms;
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("Sophia", 5);
d.Add("Mary", 14);
d.Add("Jacob", 40);
string str = "";
foreach (KeyValuePair<string, int> item in d)
{
str += item.Key + "," + item.Value + ". ";
}
MessageBox.Show(str); //Sophia,5. Mary,14. Jacob,40.

continue will skip one specific step, break will stop the loop.
foreach (KeyValuePair<string, int> item in d)
{
if (item.Key == "Mary") continue;
str += item.Key + "," + item.Value + ". ";
}
MessageBox.Show(str); //Sophia,5. Jacob,40.
foreach (KeyValuePair<string, int> item in d)
{
if (item.Key == "Mary") break;
str += item.Key + "," + item.Value + ". ";
}
MessageBox.Show(str); //Sophia,5.

Loops through an array.
using System.Windows.Forms;
int[] arr = { 1, 2, 3, 4, 5, 6 };
string str = "";
foreach(int i in arr)
{
str += i.ToString() + ", ";
}
MessageBox.Show(str); //1, 2, 3, 4, 5, 6,

Loops through a List.
using System.Collections.Generic;
using System.Windows.Forms;
List<string> l = new List<string>();
l.Add("Monday");
l.Add("Tuesday");
l.Add("Wednesday");
string str = "";
foreach(string i in l)
{
str += i + ", ";
}
MessageBox.Show(str); //Monday, Tuesday, Wednesday,



endmemo.com © 2024  | Terms of Use | Privacy | Home