33.字典如何一键对多值
33.1 题目
C#中的Dictionary不支持相同键存储。如果想要一个键对应多个值,如何处理?
33.2 深入解析
在C#中,Dictionary是一种键值对集合,每个键必须是唯一的,因此不支持相同键存储。如果想要一个键对应多个值,可以使用 Dictionary<TKey, List<TValue>> 或 Dictionary<TKey, HashSet<TValue>> 等数据结构来处理。
//一键对多值 List
Dictionary<string, List<Player>> dic = new Dictionary<string, List<Player>>();
//一键对多值 数组
Dictionary<string, Player[]> dic2 = new Dictionary<string, Player[]>();
//一键对多值 链表
Dictionary<string, LinkedList<Player>> dic3 = new Dictionary<string, LinkedList<Player>>();
//一键对多值 栈
Dictionary<string, Stack<Player>> dic4 = new Dictionary<string, Stack<Player>>();
//一键对多值 队列
Dictionary<string, Queue<Player>> dic5 = new Dictionary<string, Queue<Player>>();
下面是使用 Dictionary<TKey, List<TValue>> 的示例代码:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个 Dictionary,键为 string 类型,值为 List<int> 类型
Dictionary<string, List<int>> multiValueDict = new Dictionary<string, List<int>>();
// 向 Dictionary 中添加键值对
AddKeyValuePair(multiValueDict, "key1", 1);
AddKeyValuePair(multiValueDict, "key1", 2);
AddKeyValuePair(multiValueDict, "key2", 3);
AddKeyValuePair(multiValueDict, "key2", 4);
// 打印所有键值对
foreach (var pair in multiValueDict)
{
Console.Write($"{pair.Key}: ");
foreach (var value in pair.Value)
{
Console.Write($"{value} ");
}
Console.WriteLine();
}
}
// 向 Dictionary 中添加键值对,如果键已存在,则将值添加到对应的 List 中
static void AddKeyValuePair(Dictionary<string, List<int>> dict, string key, int value)
{
if (!dict.ContainsKey(key))
{
dict[key] = new List<int>();
}
dict[key].Add(value);
}
}
在上面的示例中,我们创建了一个 Dictionary<string, List<int>>,其中键为 string 类型,值为 List<int> 类型,用于存储一个键对应多个值的情况。然后通过自定义的 AddKeyValuePair 方法来添加键值对,并确保每个键对应的值都被存储在列表中。
通过这种方式,就可以有效地处理一个键对应多个值的情况。
33.3 答题示例
在C#中处理一个键对应多个值的场景,核心是将
Dictionary的值类型定义为集合类型,让单个键映射到一个存储多个元素的集合。常用方式如下:
选择合适的集合作为值类型:根据需求选择
List<T>(允许重复值、有序)、HashSet<T>(不允许重复值、查询快)、Queue<T>(先进先出)等作为Dictionary的值类型,例如Dictionary<TKey, List<TValue>>或Dictionary<TKey, HashSet<TValue>>。添加键值对时的处理逻辑:添加数据时,先判断键是否已存在。若不存在,为该键初始化一个空集合;若已存在,直接向对应的集合中添加新值。例如:
- 若使用
List<T>,可允许同一键下有重复值;- 若使用
HashSet<T>,则会自动去重,适合需要唯一值的场景。访问数据:通过键获取对应的集合后,遍历集合即可获取该键对应的所有值。
这种方式既保留了
Dictionary的快速查询特性,又能满足一键多值的需求,实际开发中可根据值是否需要去重、是否有序等需求选择具体的集合类型。
33.4 关键词联想
- Dictionary<TKey, TValue>
集合嵌套(如List<T>、HashSet<T>、Queue<T>)- 一键多值
- ContainsKey方法
- 集合初始化
List<T>(允许重复值)HashSet<T>(去重)- 键值对映射
- Add方法
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 785293209@qq.com