键值对

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

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

3.c#中字典的对象有两个:SortedListHashtable

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();
}

Hashtable的值输出时无序的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值