Dictionary用法
2015-12-17 15:24
316 查看
要使用Dictionary集合,需要导入C#泛型命名空间
System.Collections.Generic(程序集:mscorlib)
Dictionary的描述
1、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
2、任何键都必须是唯一的
3、键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
4、Key和Value可以是任何类型(string,int,custom class 等)
Dictionary常用用法:以 key 的类型为 int , value的类型为string 为例
1、创建及初始化
Dictionary<int,string>myDictionary=newDictionary<int,string>();
2、添加元素
myDictionary.Add(1,"C#");
myDictionary.Add(2,"C++");
myDictionary.Add(3,"ASP.NET");
myDictionary.Add(4,"MVC");
3、通过Key查找元素
if(myDictionary.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
4、通过KeyValuePair遍历元素
foreach(KeyValuePair<int,string>kvp in myDictionary)
{
Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}
5、仅遍历键 Keys 属性
Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;
foreach(intkeyinkeyCol)
{
Console.WriteLine("Key = {0}", key);
}
6、仅遍历值 Valus属性
Dictionary<int,string>.ValueCollection valueCol=myDictionary.Values;
foreach(stringvalueinvalueCol)
{
Console.WriteLine("Value = {0}", value);
}
7、通过Remove方法移除指定的键值
myDictionary.Remove(1);
if(myDictionary.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
else
{
Console.WriteLine("不存在 Key : 1");
}
System.Collections.Generic(程序集:mscorlib)
Dictionary的描述
1、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
2、任何键都必须是唯一的
3、键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
4、Key和Value可以是任何类型(string,int,custom class 等)
Dictionary常用用法:以 key 的类型为 int , value的类型为string 为例
1、创建及初始化
Dictionary<int,string>myDictionary=newDictionary<int,string>();
2、添加元素
myDictionary.Add(1,"C#");
myDictionary.Add(2,"C++");
myDictionary.Add(3,"ASP.NET");
myDictionary.Add(4,"MVC");
3、通过Key查找元素
if(myDictionary.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
4、通过KeyValuePair遍历元素
foreach(KeyValuePair<int,string>kvp in myDictionary)
{
Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}
5、仅遍历键 Keys 属性
Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;
foreach(intkeyinkeyCol)
{
Console.WriteLine("Key = {0}", key);
}
6、仅遍历值 Valus属性
Dictionary<int,string>.ValueCollection valueCol=myDictionary.Values;
foreach(stringvalueinvalueCol)
{
Console.WriteLine("Value = {0}", value);
}
7、通过Remove方法移除指定的键值
myDictionary.Remove(1);
if(myDictionary.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
else
{
Console.WriteLine("不存在 Key : 1");
}
相关文章推荐
- rk3288_lubuntu_img制作步骤
- Web Services 指南之:什么是 Web Services?
- (nehe教程)不使用auxDIBImageLoad,加载bmp文件
- 彻底明白Android中AIDL及其使用
- 巴什博奕
- 如何循环遍历winForm中所有窗体的名称,所有活动的窗体
- Win7配置CUDA并搭建基于Theano框架的GPU加速环境
- Linux 快捷键
- linux less命令
- hdu1358Period(KMP)
- cin输入的问题
- android-async-http AsyncHttpClient介绍和使用
- Android开发艺术-第六章Drawable读书笔记
- Genymotion 5.0 ARM-Translation
- removing-删除
- NFC基础
- Android View移动的六种方法小结
- 360搜索联盟推出“图片排行榜”新广告样式
- 1003. 我要通过!(20)练习
- UITableViewCell自适应内容高度