ASP.NET中Dictionary的基本用法

本文详细介绍了C#中Dictionary类的基本用法,包括如何声明、添加元素、检查键的存在性、删除元素、获取键值对数量及遍历键值对等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        //Dictionary位于System.Collections.Generic命名空间之下

 

        /*

         * 使用Dictionary之前必须引用System.Collections.Generic命名空间;

         * 使用Dictionary时必须声明其键和值的数据类型(可以为任意类型);

         */

 

        //声明实例化Dictionary为dic

        System.Collections.Generic.Dictionary<intstring> dic = new System.Collections.Generic.Dictionary<intstring>();

 

        //为dic添加键和值

        dic.Add(100, "quber100");

        dic.Add(200, "quber200");

 

        //检查是否存在300这个键

        if (!dic.ContainsKey(300))

        {

            //新增加300(键)和对应的quber300(值)

            dic.Add(300, "quber300");

        }

 

        //移除dic键为300的项

        dic.Remove(300);

 

        //获取dic键值对总数

        int dicCount = dic.Count;

 

        Response.Write("循环获取dic中的键和值:<br/>");

        //循环获取dic中的键和值

        foreach (KeyValuePair<intstring> keyDic in dic)

        {

            Response.Write("key:" + keyDic.Key + ",value:" + keyDic.Value + "<br/>");

        }

        Response.Write("<hr/><br/>");

 

        Response.Write("循环获取dic中的键:<br/>");

        //循环获取dic中的键

        Dictionary<intstring>.KeyCollection keyDics = dic.Keys;

        foreach (int iKey in keyDics)

        {

            Response.Write("key:" + iKey + "<br/>");

        }

        Response.Write("<hr/><br/>");

 

        Response.Write("另一种方法循环获取dic中的键:<br/>");

        //循环获取dic中的键

        foreach (int iKey in dic.Keys)

        {

            Response.Write("key:" + iKey + "<br/>");

        }

        Response.Write("<hr/><br/>");

 

        Response.Write("循环获取dic中的值:<br/>");

        //循环获取dic中的值

        Dictionary<intstring>.ValueCollection valueDics = dic.Values;

        foreach (string strValue in valueDics)

        {

            Response.Write("value:" + strValue + "<br/>");

        }

        Response.Write("<hr/><br/>");

 

        Response.Write("另一种方法循环获取dic中的值:<br/>");

        //循环获取dic中的值

        foreach (string strValue in dic.Values)

        {

            Response.Write("value:" + strValue + "<br/>");

        }

        Response.Write("<hr/><br/>");

 

        Response.Write("获取dic中单个键和值:<br/>");

        Response.Write("key:100,value:" + dic[100] + "<br/>");

        Response.Write("<hr/><br/>");

 

        Response.Write("检查dic中是否存在键(100),并返回其值dicStr:<br/>");

        //检查dic中是否存在键(100),并返回其值dicStr

        string dicStr = string.Empty;

        if (dic.TryGetValue(100, out dicStr))

        {

            Response.Write("OK");

        }

        else

        {

            Response.Write("NO");

        }

        Response.Write("<hr/><br/>");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值