IDictionary<TKey,TValue>数据字典使用讲解
接口描述
Represents a nongeneric collection of key/value pairs.[代表一个非泛型的键/值对的集合]。在System.Collections.Generic包下面。所在程序集为mscorlib.dll中。
语法
public Interface IDictionary<TKey,TValue>:ICollection<KeyValuePair<TKey,TValue>>,IEnumerable<KeyValuePair<TKey,TValue>>,IEnumberable备注 IDictionary<TKey, TValue>接口是键/值对的泛型集合的基接口。每个元素都是一个存储在KeyValuePair<TKey, TValue>对象中的键/值对。每一对都必须有唯一的键。实现在是否允许key为null方面有所不同。此值可以为null,并且不必是唯一的。IDictionary<TKey, TValue>接口允许对所包含的键和值进行枚举,但这并不意味着任何特定的排序顺序。C# 语言中的foreach语句(在 Visual Basic 中为For Each,在 C++ 中为for each)需要集合中每个元素的类型。由于IDictionary<TKey, TValue>的每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型。而是KeyValuePair<TKey, TValue>类型。代码案例如下:
foreach(KeyValuePair<int,string>kvpinmyDictionary){Console.WriteLine("Key={0},Value={1}",kvp.Key,kvp.Value);}
注:foreach语句是对枚举数的包装,它只允许从集合中读取,不允许写入集合。
方法列表:
将某项添加到ICollection<T>中。(继承自ICollection<T>。)Add(TKey,TValue)在IDictionary<TKey, TValue>中添加一个带有所提供的键和值的元素。Clear()
清空ICollection<T>中的所有元素。Contains确认ICollection<T>集合中是否有特定的值ContainsKey
确认IDictionary<TKey, TValue>集合中是否包含指定键元素。CopyTo从特定的Array索引开始,将ICollection<T>的元素复制到一个Array中。(继承自ICollection<T>。)GeEnumurator
返回一个循环访问集合的枚举器。(继承自IEnumerable<T>。)Remove(T)
移除指定元素
Remove(TKey)移除指定键的元素TryGetValue获得与指定键关联的元素值
注:扩展方法可到官方MSDN查看:http://msdn.microsoft.com/zh-cn/library/8hyehyw5(v=vs.110).aspx
//Createanewdictionaryofstrings,withstringkeys,//andaccessitthroughtheIDictionarygenericinterface.IDictionary<string,string>openWith=newDictionary<string,string>();//Addsomeelementstothedictionary.Thereareno//duplicatekeys,butsomeofthevaluesareduplicates.openWith.Add("txt","notepad.exe");openWith.Add("bmp","paint.exe");openWith.Add("dib","paint.exe");openWith.Add("rtf","wordpad.exe");//TheAddmethodthrowsanexceptionifthenewkeyis//alreadyinthedictionary.try{openWith.Add("txt","winword.exe");}catch(ArgumentException){Console.WriteLine("AnelementwithKey=\"txt\"alreadyexists.");}//TheItempropertyisanothernamefortheindexer,soyou//canomititsnamewhenaccessingelements.Console.WriteLine("Forkey=\"rtf\",value={0}.",openWith["rtf"]);//Theindexercanbeusedtochangethevalueassociated//withakey.openWith["rtf"]="winword.exe";Console.WriteLine("Forkey=\"rtf\",value={0}.",openWith["rtf"]);//Ifakeydoesnotexist,settingtheindexerforthatkey//addsanewkey/valuepair.openWith["doc"]="winword.exe";//Theindexerthrowsanexceptioniftherequestedkeyis//notinthedictionary.try{Console.WriteLine("Forkey=\"tif\",value={0}.",openWith["tif"]);}catch(KeyNotFoundException){Console.WriteLine("Key=\"tif\"isnotfound.");}//Whenaprogramoftenhastotrykeysthatturnoutnotto//beinthedictionary,TryGetValuecanbeamoreefficient//waytoretrievevalues.stringvalue="";if(openWith.TryGetValue("tif",outvalue)){Console.WriteLine("Forkey=\"tif\",value={0}.",value);}else{Console.WriteLine("Key=\"tif\"isnotfound.");}//ContainsKeycanbeusedtotestkeysbeforeinserting//them.if(!openWith.ContainsKey("ht")){openWith.Add("ht","hypertrm.exe");Console.WriteLine("Valueaddedforkey=\"ht\":{0}",openWith["ht"]);}//Whenyouuseforeachtoenumeratedictionaryelements,//theelementsareretrievedasKeyValuePairobjects.Console.WriteLine();foreach(KeyValuePair<string,string>kvpinopenWith){Console.WriteLine("Key={0},Value={1}",kvp.Key,kvp.Value);}//Togetthevaluesalone,usetheValuesproperty.ICollection<string>icoll=openWith.Values;//TheelementsoftheValueCollectionarestronglytyped//withthetypethatwasspecifiedfordictionaryvalues.Console.WriteLine();foreach(stringsinicoll){Console.WriteLine("Value={0}",s);}//Togetthekeysalone,usetheKeysproperty.icoll=openWith.Keys;//TheelementsoftheValueCollectionarestronglytyped//withthetypethatwasspecifiedfordictionaryvalues.Console.WriteLine();foreach(stringsinicoll){Console.WriteLine("Key={0}",s);}//UsetheRemovemethodtoremoveakey/valuepair.Console.WriteLine("\nRemove(\"doc\")");openWith.Remove("doc");if(!openWith.ContainsKey("doc")){Console.WriteLine("Key\"doc\"isnotfound.");}Console.ReadLine();
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。