IDictionary的操作

来源:互联网 发布:淘宝帐号买卖 编辑:程序博客网 时间:2024/05/17 07:06
 
//注test1是個對象包含Name和Type屬性及SS()方法
        test1 value1;
        IDictionary<string, test1> iDict = new Dictionary<string, test1>();
        iDict["a1"] = new test1("aa1", "str");//第一種附值的方法
        iDict.Add("a2", new test1("aa2", "int"));//第二種添加方法
        Response.Write(iDict["a1"].Type + "<br/>" + iDict["a1"].Name + ";<br/>" + iDict["a2"].Type + iDict["a2"].Name);//第一種取值的方法
        iDict["a2"] = new test1("ab2", "int2");
        Response.Write("2:" + iDict["a2"].Type + iDict["a2"].Name);
        Label1.Text = iDict["a2"].SS();
        if (iDict.TryGetValue("a2", out value1))//第二種取值的方法
        {
            Response.Write("<br/>3:" + value1.Name);
        }
        else
        {
            Response.Write("the index is not exist");
        }
        if(iDict.ContainsKey("a3"))//檢查key是否存在
        {
            Response.Write("<br/>存在a1");
        }
        foreach (KeyValuePair<string, test1> KVP in iDict)//迭代取得該IDictionary
        {
            Response.Write("<br/>begin:" + KVP.Key + KVP.Value.Name);
        }
        ICollection<test1> IC = iDict.Values;//取得所有的值
        foreach (test1 tt in IC)
        {
            Response.Write("<br/>end:" + tt.Type);
        }
        //test1[] id ={ new test1("dd1", "int4"), new test1("dd2", "int5") };
        //foreach (test1 tt in id)
        //{
        //    Response.Write("<br/>end2:" + tt.Name);
        //}
        iDict.Remove("a1");//移除key="a1"的值
        ICollection<string> ICC = iDict.Keys;//取得所有的key
        foreach (string K in ICC)
        {
            Response.Write("<br/>Key:" + K);
        }
原创粉丝点击