什么是foreach
-
forech就是传说中的增强for循环或者称作foreach循环
-
forech对遍历字典或集合具备天然优势,效率高过for循环
foreach 操作数组
public void TestFor1()
{
int[] ints = { 1, 2, 3 };
foreach (int item in ints)
{
Console.WriteLine(item.ToString());
}
}
foreach 操作集合
public void TestFor2()
{
List<int> intList = new List<int>() { 1, 2, 3, 4, 5 };
foreach (int item in intList)
{
Console.WriteLine(item.ToString());
}
}
foreach 操作字典
public void TestFor3()
{
Dictionary<string, string> dic = new Dictionary<string, string>()
{
{ "A","aa"},
{ "B","bb"},
{ "C","cc"},
{ "D","dd" },
};
//KeyValuePair<string,string> 键值对的类型与字典中的一致
foreach (KeyValuePair<string,string> item in dic)
{
string key = item.Key;
string value = item.Value;
Console.WriteLine("Key:{0}\tValue:{1}", key, value);
}