当前第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的用法详解的详细内容!
返回前面的内容
相关阅读 >>
使用c#操作windowad之的windows用户组
c#中值类型与引用类型的详细介绍
c#中关于静态与非静态方法的区别介绍
.net framework类库的主要功能是什么?
c#实现与现有.net事件桥接的简单代码
c#中五种访问修饰符作用范围实例详解
.net是干嘛的和java的区别
c# 5.0引入了两个关键字 --async和await
.net中的错误处理机制是什么?
c#如何实现自动更新本地程序的实例分析
更多相关阅读请进入《Dictionary》频道 >>
清华大学出版社
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。
转载请注明出处:木庄网络博客 » C#中关于Dictionary的用法详解