您的位置:首页 > 其它

for 遍历 Dictionary

2015-12-19 16:30 239 查看

使用for来遍历Dictionary

ToArray方法:

ToArray等于把Dictionary拷贝了一份

 

使用Linq的方法

Enumerable.ElementAt<TSource>  (IEnumerable<TSource>, Int32)

参考:https://msdn.microsoft.com/zh-cn/library/bb299233%28v=vs.110%29.aspx

 

方法代码:
public static void Main(string[] args)
{
Dictionary<string,string> dictionary =new Dictionary<string, string>();
dictionary["engine1"] = "unity";
dictionary["engine2"] = "cocos";

//方法一
var array = dictionary.ToArray();
for (int idx = 0; idx < array.Count(); idx++)
{
var itemKey = array[idx].Key;
var itemValue = array[idx].Value;
Console.Write("key:{0} ,value:{1}\n", itemKey, itemValue);
}

//方法二
for (int index = 0; index < dictionary.Count; index++)
{
//根据索引获取
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
Console.Write("\nkey:{0} ,value:{1}\n", itemKey, itemValue);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: