C# Dictionary用法总结
1、用法1: 常规用
增加键值对之前需要判断是否存在该键,如果已经存在该键而且不判断,将抛出异常。所以这样每次都要进行判断,很麻烦,在备注里使用了一个扩展方法
public
static
void
DicSample1()
{
Dictionary<String,String> pList =
new
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; margin:0px!important; outline:0px!important; overflow:visible!important; padding:0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,String>();
try
{
if
(pList.ContainsKey(
"Item1"
) ==
false
)
{
pList.Add(
,
"ZheJiang"
);
}
"Item2"
)==
)
{
"ShangHai"
);
}
else
{
pList[
] =
;
}
"Item3"
)
{
"BeiJiang"
);
}
}
catch
(System.Exception e)
{
Console.WriteLine(
"Error: {0}"
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; margin:0px!important; outline:0px!important; overflow:visible!important; padding:0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,e.Message);
}
//判断是否存在相应的key并显示
))
{
"Output: "
+ pList[
]);
}
//遍历Key
foreach
(
var
key
in
pList.Keys)
{
"Output Key: {0}"
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; margin:0px!important; outline:0px!important; overflow:visible!important; padding:0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,key);
}
//遍历Value
(String value
pList.Values)
{
"Output Value: {0}"
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; margin:0px!important; outline:0px!important; overflow:visible!important; padding:0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,value);
}
//遍历Key和Value
dic
pList)
{
"Output Key : {0},Value : {1} "
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; margin:0px!important; outline:0px!important; overflow:visible!important; padding:0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,dic.Key,dic.Value);
}
}
|
Student类:
4 备注:Dictionary的扩展方法使用
扩展方法所在的类
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。