当前第2页 返回上一页
创建及初始化
1 | Dictionary< int , string > myDictionary= new Dictionary< int , string >();
|
添加元素
1 2 3 4 5 6 7 | myDictionary.Add(1, "C#" );
myDictionary.Add(2, "C++" );
myDictionary.Add(3, "ASP.NET" );
myDictionary.Add(4, "MVC" );
|
通过Key查找元素
1 2 3 4 5 6 7 | if (myDictionary.ContainsKey(1))
{
Console.WriteLine( "Key:{0},Value:{1}" , "1" , myDictionary[1]);
}
|
通过KeyValuePair遍历元素
1 2 3 4 5 6 7 | foreach (KeyValuePair< int , string > kvp in myDictionary)
{
Console.WriteLine( "Key = {0}, Value = {1}" ,kvp.Key, kvp.Value);
}
|
仅遍历键 Keys 属性
1 2 3 4 5 6 7 | Dictionary< int , string >.KeyCollection keyCol = myDictionary.Keys; foreach (intkeyinkeyCol)
{
Console.WriteLine( "Key = {0}" , key);
}
|
仅遍历值 Valus属性
1 2 3 4 5 6 7 | Dictionary< int , string >.ValueCollection valueCol = myDictionary.Values; foreach (stringvalueinvalueCol)
{
Console.WriteLine( "Value = {0}" , value);
}
|
通过Remove方法移除指定的键值
1 2 3 4 5 6 7 8 9 10 11 | myDictionary.Remove(1); if (myDictionary.ContainsKey(1))
{
Console.WriteLine( "Key:{0},Value:{1}" , "1" , myDictionary[1]);
} else {
Console.WriteLine( "不存在 Key : 1" );
}
|
4.其它常见属性和方法的说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Comparer:
Count:
Item:
Keys:
Values:
Add:
Clear:
ContainsKey:
ContainsValue:
GetEnumerator:
GetType:
Remove:
ToString:
TryGetValue:
|
以上就是C#中关于Dictionary的用法详解的详细内容!
返回前面的内容
相关阅读 >>
.net中的序列化详解
c#中关于扩展方法的实例分析
.net中关于接口和类之间的区别介绍
c#中实现复制与删除文件的方法
关于.net(c#)正确读取中文编码文件的实例教程
c#基础之操作优化实例教程
linux下搭建.net core环境方法步骤
在linux下搭建.net core开发环境教程
.net mvc 使用ueditor上传图片
比较c#和java中面向对象语法的区别
更多相关阅读请进入《Dictionary》频道 >>
清华大学出版社
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。
转载请注明出处:木庄网络博客 » C#中关于Dictionary的用法详解