您的位置:首页 > 运维架构

[.NET] 如何利用 for loop 寻访 Dictionary (Linq)

2010-10-19 14:52 155 查看
如题,有时候并无法使用foreach去得到Dictionary中的key,value

可使用Linq转成List,然后使用for loop取得key value



Dictionary<int, string> myDict = new Dictionary<int, string>()
         {
             { 2, "This" },
             { 1, "is" },
             { 5, "radio" },
             { 12, "clash" },
         };

var target = myDict.ToList();

for ( int index=0; index < target.Count; index++ )
    Console.WriteLine( "Key: {0,2} Value : {1}", target[index].Key, target[index].Value );

/* Output
Key:  2 Value : This
Key:  1 Value : is
Key:  5 Value : radio
Key: 12 Value : clash
 */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: