C#:Dictionary类型数组

在C#中,如果你想将字典(Dictionary)作为数组的一个元素。

方法1:直接声明字典数组

例如:

Dictionary<int, string>\[\] dictArray = new Dictionary<int, string>3;

// 初始化字典数组的每个元素

for (int i = 0; i < dictArray.Length; i++)

{

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

}

// 示例:向第一个字典添加元素

dictArray0.Add(1, "One");

dictArray0.Add(2, "Two");

方法2:使用List<Dictionary<TKey, TValue>>

如果你不确定数组的大小,或者想要更灵活地管理字典集合,可以使用List<Dictionary<TKey, TValue>>:

List<Dictionary<int, string>> dictList = new List<Dictionary<int, string>>();

// 添加一个新字典到列表中

dictList.Add(new Dictionary<int, string>());

dictList.Add(new Dictionary<int, string>());

// 示例:向第一个字典添加元素

dictList0.Add(1, "One");

dictList0.Add(2, "Two");

方法3:在数组中使用匿名类型或自定义类型封装字典

如果需要在数组中存储不同类型的对象,包括字典,你可以使用匿名类型或自定义类来封装字典:

// 使用匿名类型

var array = new {

Dict1 = new Dictionary<int, string> { { 1, "One" }, { 2, "Two" } },

Dict2 = new Dictionary<int, string> { { 3, "Three" }, { 4, "Four" } }

};

// 或者使用自定义类型

public class DictWrapper

{

public Dictionary<int, string> Dict { get; set; }

}

DictWrapper\[\] dictArray = new DictWrapper2;

dictArray0 = new DictWrapper { Dict = new Dictionary<int, string> { { 1, "One" }, { 2, "Two" } } };

dictArray1 = new DictWrapper { Dict = new Dictionary<int, string> { { 3, "Three" }, { 4, "Four" } } };

方法4:使用元组(适用于简单的键值对)

对于简单的键值对集合,你可以使用元组(Tuple)或值元组(ValueTuple):

(Dictionary<int, string>, Dictionary<int, string>)\[\] dictTuples = new (Dictionary<int, string>, Dictionary<int, string>)2;

dictTuples0 = (new Dictionary<int, string> { { 1, "One" }, { 2, "Two" } }, null); // 示例:第一个位置存储一个字典,第二个为null或另一个字典等。

dictTuples1 = (new Dictionary<int, string> { { 3, "Three" }, { 4, "Four" } }, null); // 同上。

相关推荐
无限的鲜花17 分钟前
反射(原创推荐)
java·开发语言
IT二叔33 分钟前
Java项目部署-03-teamcity-cicd-docker镜像流水线方式部署
java·ci/cd·持续部署
yongche_shi44 分钟前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
一路向北he1 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
超级数据查看器1 小时前
超级数据查看器 v10.0 发布
java·大数据·数据库·sqlite·安卓
AI行业学习2 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++
折哥的程序人生 · 物流技术专研2 小时前
《Java 100 天进阶之路》第50篇:阻塞队列与并发容器(2026版)
java·面试题·java进阶·blockingqueue·并发容器·集合源码·java100天进阶
ai_coder_ai3 小时前
编写自动化脚本,在自己后端服务中使用Open Api进行设备相关操作
java·运维·自动化
大圣编程3 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
硕风和炜3 小时前
【LeetCode: 2492. 两个城市间路径的最小分数 + DFS】
java·算法·leetcode·深度优先·dfs·bfs·并查集