只知道i是多少,并不知道key是什么,如何从一个Dictionary里取得第i个key和Value?有什么好的方法

解决方案 »

  1.   


    int i = 2;
    Dictionary<string, Class1> cl = new Dictionary<string, Class1>();
                Class1 s1 = new Class1("张三", 25);
                Class1 s2 = new Class1("李四", 26);
                Class1 s3 = new Class1("家六", 27);
                cl.Add(s1.Name, s1);
                cl.Add(s2.Name, s2);
                cl.Add(s3.Name, s3);
    int idx = 0;
                foreach (KeyValuePair<string, Class1> a in cl)
                {
    if(idx==i)
    //to do;
                    MessageBox.Show(a.Value.Age.ToString() + "  " + a.Value.Name.ToString());
    idx++;
                }
      

  2.   


    private void button1_Click(object sender, EventArgs e)
      {
      Dictionary<string, object> objs = new Dictionary<string, object>();
      objs.Add("name","eric");
      objs.Add("age",18);
      Text(objs);
      }
      public void Text(Dictionary<string, object> objs)
      {  Dictionary<string, object>.KeyCollection names = objs.Keys;
      string keyValue="";
      foreach (string name in names)
      {
      string value = objs[name].ToString();
      keyValue = keyValue + name + ":" + value + " ";
      }
      MessageBox.Show(keyValue);  }
    结果为:name:eric age:18 
      

  3.   

    本来就是键值对的数据结构,你要按序号来存取的话,要么,把顺序号作为key,要么就换成List吧
      

  4.   

    dictionary不能通过索引访问只能自己控制了.
    要不tolist下然后自己搞了
      

  5.   

    KeyValuePair
    Or
    dictionary[key]=value
      

  6.   

    Dictionary是二叉树,你要直接得索引位的值,那你又按什么顺序来定索引呢?或者加个List变量,保存时也在list中保存一份,就能得到index时的值了