当前第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?core?以及与?.net?framework的关系(图)
c#如何通过对象属性名修改值的实例
pdb是什么文件?
.net core mvc实现一个在线房间棋牌游戏微信支付和及时通讯的简易框架
.net多线程编程中的误用点分析
在.net项目中使用postsharp
.net页面局部更新引发的思考
c#编程如何获取电脑硬件信息的方法?
c#中使用反射以及特性简化的实例代码
c#中datetime与时间戳转换的实例代码
更多相关阅读请进入《Dictionary》频道 >>
清华大学出版社
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。
转载请注明出处:木庄网络博客 » C#中关于Dictionary的用法详解