.NET(C#)如何遍历Dictionary

C#开发 2014-11-05 19780阅读 0评论 0收藏 收藏本文
我们知道.NET中的Dictionary是键/值对的集合,使用起来也是比较方便,Dictionary也可以用KeyValuePair来迭代遍历,具体如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryIterateDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      IterateDictionaryMethod();
      Console.ReadKey();
    }

    static void IterateDictionaryMethod()
    {
      var dict = new Dictionary<string, string>();
      for (int i = 0; i < 10; i++)
      {
        dict.Add(string.Format("key_{0}", i), string.Format("value_{0}", i));
      }

      //foreach (var item in dict)
      foreach (KeyValuePair<string, string> item in dict)
      {
        Console.WriteLine("key:{0},value:{1}", item.Key, item.Value);
      }

      //当然最便捷的是var
      //foreach (var item in dict)
      //{
      //  Console.WriteLine("key:{0},value:{1}", item.Key, item.Value);
      //}
    }
  }
}
运行结果为:
key:key_0,value:value_0
key:key_1,value:value_1
key:key_2,value:value_2
key:key_3,value:value_3
key:key_4,value:value_4
key:key_5,value:value_5
key:key_6,value:value_6
key:key_7,value:value_7
key:key_8,value:value_8
key:key_9,value:value_9
 

转载请注明:图享网 » .NET(C#)如何遍历Dictionary

文章评论

获取验证码