C#:Dictionary类型数组

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

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

例如:

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

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

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

{

dictArray[i] = new Dictionary<int, string>();

}

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

dictArray[0].Add(1, "One");

dictArray[0].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>());

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

dictList[0].Add(1, "One");

dictList[0].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 DictWrapper[2];

dictArray[0] = new DictWrapper { Dict = new Dictionary<int, string> { { 1, "One" }, { 2, "Two" } } };

dictArray[1] = 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];

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

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

相关推荐
菜鸟233号27 分钟前
力扣647 回文子串 java实现
java·数据结构·leetcode·动态规划
qq_124987075333 分钟前
基于Java Web的城市花园小区维修管理系统的设计与实现(源码+论文+部署+安装)
java·开发语言·前端·spring boot·spring·毕业设计·计算机毕业设计
h7ml42 分钟前
查券返利机器人的OCR识别集成:Java Tesseract+OpenCV优化图片验证码的自动解析方案
java·机器人·ocr
野犬寒鸦43 分钟前
从零起步学习并发编程 || 第五章:悲观锁与乐观锁的思想与实现及实战应用与问题
java·服务器·数据库·学习·语言模型
Volunteer Technology1 小时前
Sentinel的限流算法
java·python·算法
岁岁种桃花儿1 小时前
SpringCloud从入门到上天:Nacos做微服务注册中心
java·spring cloud·微服务
jdyzzy1 小时前
什么是 JIT 精益生产模式?它与传统的生产管控方式有何不同?
java·大数据·人工智能·jit
Chasmれ1 小时前
Spring Boot 1.x(基于Spring 4)中使用Java 8实现Token
java·spring boot·spring
froginwe111 小时前
Python 条件语句
开发语言
汤姆yu1 小时前
2026基于springboot的在线招聘系统
java·spring boot·后端