版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的
KeyValuePair
通常在KeyValuePair的构造函数中传入键和值作为参数,例如下面的语句定义了键为int、值为string的KeyValuePair,并赋予了初始值:
KeyValuePair<int, string> newKeyValuePair = new KeyValuePair<int, String>(键, 值);
注意:KeyValuePair的Key和Value属性是只读的。
KeyValuePair对应的键值对集合是Dictionary。
【例 4.14】【项目:code4-014】 KeyValuePair的用法。
static void Main(string[] args)
{
int deKey = 1;
string deValue = "水调歌头";
KeyValuePair<int, string> dePoem = new KeyValuePair<int, String>(deKey, deValue);
Console.WriteLine("诗词序号:" + dePoem.Key);
Console.WriteLine("诗词标题:" + dePoem.Value);
string deKey1 = "春晓";
string deValue1 = "孟浩然";
KeyValuePair<string, string> dePoem1 = new KeyValuePair<string, string>(deKey1, deValue1);
Console.WriteLine("诗词标题:" + dePoem1.Key);
Console.WriteLine("诗词作者:" + dePoem1.Value);
Console.ReadKey();
}
运行输出结果同【例 4.12】。
Dictionary类是表示根据键的哈希代码进行组织的键值对(Key/Value)的集合。
Dictionary类提供的属性和方法同HashTable类类似,操作也差不多。
【例 4.15】【项目:code4-015】 Dictionary的增、删、改、遍历、查找。
static void Main(string[] args)
{
Dictionary<string, string> studentDic = new Dictionary<string, string>();
Console.WriteLine("请输入一组数据:");
int ID;
string studentID;
ID = 0;
string inputLine;
inputLine = Console.ReadLine();
string studentName;
while(inputLine.Trim() != "")
{
ID += 1;
studentID = "A000" + ID;
studentName = inputLine.Trim();
Console.WriteLine("学号:" + studentID + "\t姓名:" + studentName);
//使用add方法增加键值对
studentDic.Add(studentID, studentName);
inputLine = Console.ReadLine();
}
//查找是否包含指定键
string studentIDtoFind = "A0003";
if (studentDic.ContainsKey(studentIDtoFind))
Console.WriteLine("指定键 " + studentIDtoFind + " 对应值为:" + studentDic[studentIDtoFind]);
else
Console.WriteLine("不存在指定键");
//查找是否包含指定值
string studentNametoFind = "张强";
if (studentDic.ContainsValue(studentNametoFind))
Console.WriteLine("找到指定值:"+ studentNametoFind);
else
Console.WriteLine("不存在指定值:"+ studentNametoFind);
Console.WriteLine("键值对个数:" + studentDic.Count);
//遍历键值对方法1:遍历KeyValuePair
Console.Write("输出键值对方法1: ");
foreach (KeyValuePair<string, string> singleDic in studentDic)
Console.Write(singleDic.Key + ":" + singleDic.Value + " ");
Console.Write("\r\n");
//修改键值对的值
studentDic["A0003"] = "陈廷";
Console.WriteLine("键值对个数:" + studentDic.Count);
//遍历键值对方法2:遍历Keys再获得对应Value
Console.Write("输出键值对方法2: ");
foreach (string singleKey in studentDic.Keys)
Console.Write(singleKey + ":" + studentDic[singleKey] + " ");
Console.Write("\r\n");
//移除键值对
studentDic.Remove("A0003");
Console.WriteLine("键值对个数:" + studentDic.Count);
//遍历键值对方法3:使用Dictionary
Console.Write("输出键值对方法3: ");
Dictionary<string, string>.Enumerator studentDicEnum = studentDic.GetEnumerator();
DictionaryEntry dentry;
while (studentDicEnum.MoveNext())
{
Console.Write(studentDicEnum.Current.Key + ":" + studentDicEnum.Current.Value + " ");
}
Console.Write("\r\n");
//清除集合中的所有键值对
studentDic.Clear();
Console.WriteLine("键值对个数:" + studentDic.Count);
Console.ReadKey();
}
运行结果同【例 4.13】。
学习更多vb.net知识,请参看vb.net 教程 目录
学习更多C#知识,请参看C#教程 目录