本文实例讲述了ASP.NET中Dictionary基本用法。分享给大家供大家参考,具体如下:
//Dictionary位于System.Collections.Generic命名空间之下
/*
* 使用Dictionary之前必须引用System.Collections.Generic命名空间;
* 使用Dictionary时必须声明其键和值的数据类型(可以为任意类型);
*/
//声明实例化Dictionary为dic
System.Collections.Generic.Dictionary<
int
,
string
> dic =
new
System.Collections.Generic.Dictionary<
int
,
string
>();
//为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<
int
,
string
> keyDic
in
dic)
{
Response.Write(
"key:"
+ keyDic.Key +
",value:"
+ keyDic.Value +
"<br/>"
);
}
Response.Write(
"<hr/><br/>"
);
Response.Write(
"循环获取dic中的键:<br/>"
);
//循环获取dic中的键
Dictionary<
int
,
string
>.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<
int
,
string
>.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/>"
);
标签:
asp.net
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!