1、C#字典 Dictionary 用法
class Program
{
static void Main(string[] args)
{
//创建泛型哈希表,Key类型为int,Value类型为string
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
//1.添加元素
myDictionary.Add(1, “a”);
myDictionary.Add(2, “b”);
myDictionary.Add(3, “c”);
//2.删除元素
myDictionary.Remove(3);
//3.假如不存在元素则添加元素
if (!myDictionary.ContainsKey(4))
{
myDictionary.Add(4, “d”);
}
//4.显示容量和元素个数
Console.WriteLine(“元素个数:{0}”,myDictionary.Count);
//5.通过key查找元素
if (myDictionary.ContainsKey(1))
{
Console.WriteLine(“key:{0},value:{1}”,“1”, myDictionary[1]);
Console.WriteLine(myDictionary[1]);
}
//6.通过KeyValuePair遍历元素
foreach (KeyValuePair<int,string>kvp in myDictionary)
{
Console.WriteLine(“key={0},value={1}”, kvp.Key, kvp.Value);
}
//7.得到哈希表键的集合
Dictionary<int, string>.KeyCollection keyCol = myDictionary.Keys;
//遍历键的集合
foreach (int n in keyCol)
{
Console.WriteLine(“key={0}”, n);
}
//8.得到哈希表值的集合
Dictionary<int, string>.ValueCollection valCol = myDictionary.Values;
//遍历值的集合
foreach( string s in valCol)
{
Console.WriteLine(“value:{0}”,s);
}
//9.使用TryGetValue方法获取指定键对应的值
string slove = string.Empty;
if (myDictionary.TryGetValue(5, out slove))
{
Console.WriteLine(“查找结果:{0}”, slove);
}
else
{
Console.WriteLine(“查找失败”);
}
//10.清空哈希表
//myDictionary.Clear();
Console.ReadKey();
}
}
}
2、举例说明:
class Program
{
static void Main(string[] args)
{
// Dictionary<Dictionary<string, int>, Dictionary<int, string>> myDiction = new Dictionary<Dictionary<string, int>, Dictionary<int, string>>();//字典这样写都是可以的!
Dictionary<string, List> myDictionary = new Dictionary<string, List>();
List intData0 = new List();
intData0.Add(11); intData0.Add(21); intData0.Add(31); intData0.Add(41); intData0.Add(51);
List intData1 = new List();
intData1.Add(11); intData1.Add(22); intData1.Add(32); intData1.Add(42); intData1.Add(52);
List intData2 = new List();
intData2.Add(11); intData2.Add(23); intData2.Add(33); intData2.Add(43); intData2.Add(53);
List intData3 = new List();
intData3.Add(11); intData3.Add(24); intData3.Add(34); intData3.Add(44); intData3.Add(54);
myDictionary.Add(“张三”, intData0);
myDictionary.Add(“李四”, intData1);
myDictionary.Add(“王五”, intData2);
myDictionary.Add(“阿六”, intData3);
foreach (KeyValuePair<string ,List> item in myDictionary)
{
// Console.WriteLine(item.Key+item.Value);
switch (item.Key)
{
case “张三”:
foreach (var item1 in item.Value)
{
//Console.WriteLine("张三里面的值是: "+item1);
switch (item1)
{
case 11:
Console.WriteLine("张三里面的第一个值是: " + 11);
break;
default:
break;
}
}
break;
default:
break;
}
}
Console.ReadKey();
}
}
运行结果:
末尾寄语:
--------C#从事已经陆陆续续将近3年了,本人对字典这一块一直是心里的一个痛点,不敢说全部知道,也不说一点都不懂,一直处于朦胧状态,最近本人针对自身,重新回过头来学习了一遍C#初中高级教程,也写了一系列基础教程学习,此时此刻才总算打通这一块盲区,理解完成于今日,特此纪念!张xx!