百度空间 | 百度首页 
               
 
查看文章
 
c#中的字典(键值对)
2008-04-16 10:20

1.字典中的每个元素具备两个属性:键和值。

2.键值通过“键”排序,并可以按照键和索引访问(无说明时,默认索引从0开始),键在集合中唯一,值则可以是任意类型数据。

3.c#中字典的对象有两个:SortedList和Hashtable

eg:SortedList mylist=new SortedList();
     mylist.Add("key1","benjing");

     Hashtable mytable=new Hashtable()
     mytable.Add("key1","shandong");

4.其中SortedList为可排序的字典,当添加元素时,元素按照正确的排序顺序插入SortedList,同时索引自动进行相应的调整,移除元素亦然。

using System;
using System.Collections;
class Class1
{
    static void Main()
      {
        Hashtable mHash = new Hashtable();
        SortedList mSort = new SortedList();
        for (int i = 0; i < 15; i++)
         {
            string oKey = "Key " + i.ToString("D4");
            string oValue = "Value " + i.ToString("x4");
            mHash.Add(oKey, oValue);
            mSort.Add("Key " + i.ToString("D2"), "Val " + i.ToString("X2"));
        }

        WrHlist(mHash);
        WriteList(mSort);
        Console.ReadLine();
    }
    public static void WrHlist(Hashtable h)
     {
        IDictionaryEnumerator mIDE = h.GetEnumerator();
        while (mIDE.MoveNext())
         {
            Console.WriteLine("{0}:{1}", mIDE.Key, mIDE.Value);
        }
     }
    public static void WriteList(SortedList mSor)
       {
        Console.WriteLine(" --以下为集合中所包含的对象元素键对!!-- ");
        for (int i = 0; i < 10; i++)
           {
            Console.WriteLine("mSotr[{0}]的值为:{1}", mSor.GetKey(i), mSor["Key " +i]);
          }
       }
}

5.字典的遍历:使用DictionaryEntry对象

eg:

foreach(DictionaryEntry dic in mylist) //这里的mylist为哈希表初始化并增加键值后的集合。
{
label1.text=label2.text+dic.Value.ToString()+dic.Key.ToString();
}


类别:c#基础 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu