C#中的Dictionary字典类常用方法介绍

时间:2020-12-12 03:41:34
using System.Collections.Generic;//引用命名空间
//Dictionary可以理解为散列集合public class DictionaryTest
{
public static void Main()
{
//1.初始化
Dictionary<string, string> dicA = new Dictionary<string, string>();
//2.添加元素 key,value->学号,姓名
dicA.Add("A01", "张三");
dicA.Add("A02", "李四");
dicA.Add("B03", "王五");
dicA.Add("A03", "毛毛");
dicA.Add("B02", "张三");

//3.通过key删除元素
dicA.Remove("A03");
//4.修改值
dicA("A02")="新值";

//5.假如不存在元素则加入元素
if (! dicA.ContainsKey("A08"))
dicA.Add("A08", "哈哈");

//6.获取元素个数
int count= dicA.Count;

//7.遍历集合
foreach (KeyValuePair<string, string> kvp in dicA)
{
Console.WriteLine("学号:{0},姓名:{1}", kvp.Key, kvp.Value);
}

//8.遍历键或值的集合
Dictionary<string, string>.KeyCollection allKeys = dicA.Keys;
Console.WriteLine("最佳女主角:");
foreach (string oneKey in allKeys)
{
Console.WriteLine(oneKey);
}

//Dictionary<string, string>.ValueCollection allValues = dicA.Values;
//foreach (string oneValue in allValues)
//{
// Console.WriteLine(oneValue);
//}

//9.取值
string stuName=dicA("A01");

//10.清空
dicA.Clear();

}
}