网站域名如何查询<网站建设与运营》
2025/12/26 19:09:33 网站建设 项目流程
网站域名如何查询,目录一、核心说明二、基本模板三、常用代码示例四、常用方法与属性五、注意事项六、案例实践一、核心说明定义DictionaryTKey, TValue是泛型集合存储无序的键值对键Key唯一值Value可重复。特点键不能为null除非TKey是可空类型值可以为null。二、基本模板using System.Collections.Generic;// 声明字典DictionaryTKey, TValue dict new DictionaryTKey, TValue();// 示例键为字符串值为整数Dictionarystring, int studentScores new Dictionarystring, int();三、常用代码示例1. 添加元素studentScores.Add(Alice, 95);studentScores.Add(Bob, 88);2. 访问元素直接索引键不存在时抛出异常int aliceScore studentScores[Alice];// 953. 安全访问推荐用 TryGetValueif (studentScores.TryGetValue(Charlie, out int charlieScore)){Console.WriteLine($Charlies score: {charlieScore});}else{Console.WriteLine(Charlie not found.);}4. 修改值studentScores[Bob] 90;// Bob的分数改为905. 遍历字典foreach (KeyValuePairstring, int pair in studentScores){Console.WriteLine(${pair.Key}: {pair.Value});}6. 删除元素studentScores.Remove(Alice);// 删除键为Alice的项四、常用方法与属性方法 / 属性作业Add(TKey, TValue)添加键值对键已存在时抛出ArgumentException。Remove(TKey)删除指定键的项返回是否成功。ContainsKey(TKey)检查是否包含指定键。TryGetValue(TKey, out TValue)尝试获取值避免键不存在时抛出异常。Clear()清空所有项。Count获取键值对数量。Keys获取所有键的集合ICollectionTKey。Values获取所有值的集合ICollectionTValue五、注意事项键的唯一性添加重复键会抛出异常建议先通过ContainsKey检查或使用TryAdd studentScores.TryAdd(Alice,95);//键已存在时返回false不抛出异常性能优化初始化时指定容量如new Dictionaryint, string(100)可减少扩容开销。遍历顺序字典是无序集合遍历顺序不保证与添加顺序一致。若需有序可使用SortedDictionaryTKey, TValue。线程安全非线程安全。六、案例实践使用字典实现统计元素出现次数以及最大次数static void Main(string[] args){Listint count new Listint{1,2,3,4,5,6,5,4,3,2,1,1,1,1,7,8,9,10};Dictionaryint,int dic new Dictionaryint, int();foreach (int i in count)//统计各个元素出现的次数{if (dic.ContainsKey(i)){dic[i];}else{dic[i] 1;}}int maxCount 0;//出现次数最多元素的出现次数int maxShu count[0];//出现次数最多的元素foreach (var item in dic)//找出该元素{if (item.Value maxCount){maxCount item.Value;maxShu item.Key;}}Console.WriteLine( 统计结果为:);foreach (var t in dic){Console.WriteLine(${t.Key } 出现了 {t.Value} 次);}Console.WriteLine($出现次数最多的元素为{maxShu},出现了 {maxCount} 次);Console.ReadKey();}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询