使用Dictionary集合

要使用Dictionary集合,需要导入C#泛型命名空间  System.Collections.Generic


Dictionary常用用法:以 key 的类型为 int , value的类型为string 为例


1、创建及初始化

DictionarymyDictionary=newDictionary();

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(KeyValuePairkvp in myDictionary)

...{

Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);

}

5、仅遍历键 Keys 属性

Dictionary.KeyCollection keyCol=myDictionary.Keys;

foreach(intkeyinkeyCol)

...{

Console.WriteLine("Key = {0}", key);

}

6、仅遍历值 Valus属性

Dictionary.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");

}

其它常见属性和方法的说明:

Comparer:           获取用于确定字典中的键是否相等的 IEqualityComparer。

Count:                  获取包含在 Dictionary中的键/值对的数目。

Item:                    获取或设置与指定的键相关联的值。

Keys:                   获取包含 Dictionary中的键的集合。

Values:                获取包含 Dictionary中的值的集合。

Add:                    将指定的键和值添加到字典中。

Clear:                  从 Dictionary中移除所有的键和值。

ContainsKey:      确定 Dictionary是否包含指定的键。

ContainsValue:   确定 Dictionary是否包含特定值。

GetEnumerator:  返回循环访问 Dictionary的枚举数。

GetType:             获取当前实例的 Type。 (从 Object 继承。)

Remove:             从 Dictionary中移除所指定的键的值。

ToString:             返回表示当前 Object的 String。 (从 Object 继承。)

TryGetValue:      获取与指定的键相关联的值。

引用:http://jingyan.baidu.com/article/9989c7460ab872f648ecfeed.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容