C# 之 Dictionary 详解使用

▪ 说明

必须包含名空间 System.Collection.Generic
Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)
键必须是唯一的,而值不需要唯一的
键和值都可以是任何类型(比如:string, int, 自定义类型等等)
可以简单将 Dictionary 理解为 键值对 数据的集合

▪ 常规使用方法

// 定义

Dictionary<string, string> dictExecutes = new Dictionary<string, string>();

// 添加元素

dictExecutes.Add("bmp", "paint.exe");
dictExecutes.Add("dib", "paint.exe");
dictExecutes.Add("rtf", "wordpad.exe");
dictExecutes.Add("txt", "notepad.exe");

// 取值

Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);

// 改值

dictExecutes["rtf"] = "winword.exe";
Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);

// 遍历 KEY

foreach( string key in dictExecutes.Keys ) Console.WriteLine("Key = {0}", key);

// 遍历 VALUE

foreach( string value in dictExecutes.Values ) Console.WriteLine("value = {0}", value);

// 遍历字典

foreach( KeyValuePair<string, string> kvp in dictExecutes ) Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);

// 添加存在的元素

try{
    dictExecutes.Add("txt", "winword.exe");
}catch( ArgumentException ){
    Console.WriteLine("An element with Key = 'txt' already exists.");
}

// 删除元素

dictExecutes.Remove("doc");
if( !dictExecutes.ContainsKey("doc") ) Console.WriteLine("Key 'doc' is not found.");

// 判断键存在

if( openWith.ContainsKey("bmp") ) Console.WriteLine("An element with Key = 'bmp' exists.");

// 参数为其它类型

Dictionary<int, string[]> dictOthers = new Dictionary<int, string[]>();

dictOthers.Add(1, "1,11,111".Split(','));
dictOthers.Add(2, "2,22,222".Split(','));

Console.WriteLine(dictOthers[1][2]);

// 首先定义类

class DouCube
{
    private int _Code;
    public int Code { get{ return _Code; } set{ _Code = value; } }
    
    private string _Page;
    public string Page { get{ return _Page; } set{ _Page = value; } } 
}

// 声明并添加元素

Dictionary<int, DouCube> MyTypes = new Dictionary<int, DouCube>();

for( int i = 1; i <= 9; i++ ){
    DouCube elem = new DouCube();
    
    elem.Code = i * 100;
    elem.Page = "http://www.doucube.com/" + i.ToString() + ".html";
    
    MyTypes.Add(i, elem);
}

// 遍历元素

foreach( KeyValuePair<int, DouCube> kvp in MyTypes ){
    Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page);
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BeanGo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值