Visual Studio中的字典

目录

一、核心说明

二、基本模板

三、常用代码示例

四、常用方法与属性

五、注意事项

六、案例实践


一、核心说明

  • 定义Dictionary<TKey, TValue> 是泛型集合,存储无序的键值对,键(Key)唯一,值(Value)可重复。
  • 特点键不能为 null (除非 TKey 是可空类型),值可以为 null

二、基本模板

using System.Collections.Generic;

// 声明字典

Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();

// 示例:键为字符串,值为整数

Dictionary<string, int> studentScores = new Dictionary<string, int>();

三、常用代码示例

  1. 添加元素

studentScores.Add("Alice", 95);

studentScores.Add("Bob", 88);

  1. 访问元素(直接索引,键不存在时抛出异常)

int aliceScore = studentScores"Alice"; // 95

  1. 安全访问(推荐用 TryGetValue)

if (studentScores.TryGetValue("Charlie", out int charlieScore))

{

Console.WriteLine($"Charlie's score: {charlieScore}");

}

else

{

Console.WriteLine("Charlie not found.");

}

  1. 修改值

studentScores"Bob" = 90; // Bob的分数改为90

  1. 遍历字典

foreach (KeyValuePair<string, int> pair in studentScores)

{

Console.WriteLine($"{pair.Key}: {pair.Value}");

}

  1. 删除元素

studentScores.Remove("Alice"); // 删除键为Alice的项

四、常用方法与属性

|-----------------------------------|-----------------------------------------|
| 方法 / 属性 | 作业 |
| Add(TKey, TValue) | 添加键值对 ,键已存在时抛出 ArgumentException。 |
| Remove(TKey) | 删除指定键的项,返回是否成功。 |
| ContainsKey(TKey) | 检查是否包含指定键。 |
| TryGetValue(TKey, out TValue) | 尝试获取值,避免键不存在时抛出异常。 |
| Clear() | 清空所有项。 |
| Count | 获取键值对数量。 |
| Keys | 获取所有键 的集合(ICollection<TKey>)。 |
| Values | 获取所有值 的集合(ICollection<TValue>) |

五、注意事项

  • 键的唯一性 :添加重复键会抛出异常,建议先通过 ContainsKey 检查或使用 TryAdd: studentScores.TryAdd("Alice",95); //键已存在时返回false,不抛出异常
  • 性能优化 :初始化时指定容量(如 new Dictionary<int, string>(100))可减少扩容开销。
  • 遍历顺序 :字典是无序集合 ,遍历顺序不保证与添加顺序一致。若需有序,可使用 SortedDictionary<TKey, TValue>。
  • 线程安全:非线程安全。

六、案例实践

使用字典实现统计元素出现次数以及最大次数

static void Main(string\[\] args)

{

List<int> count = new List<int>

{

1,2,3,4,5,6,5,4,3,2,1,1,1,1,7,8,9,10

};

Dictionary<int,int> dic = new Dictionary<int, int>();

foreach (int i in count) //统计各个元素出现的次数

{

if (dic.ContainsKey(i))

{

dici++;

}

else

{

dici = 1;

}

}

int maxCount = 0; //出现次数最多元素的出现次数

int maxShu = count0; //出现次数最多的元素

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();

}

相关推荐
LinXunFeng1 小时前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
唐青枫1 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech2 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf3 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6253 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech4 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
摇滚侠4 天前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea
闪闪发亮的小星星4 天前
高斯光以及高斯光公式解释
笔记
cqbzcsq4 天前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
霸道流氓气质4 天前
Trae IDE 新手入门指南
ide