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); // 同上。

相关推荐
码农小卡拉几秒前
数据库:主键 VS 唯一索引 区别详解
java·数据库·sql
旅途中的宽~2 分钟前
【Python】pip install -v e .命令不想自动更新torch版本
开发语言·python·pip
lly2024064 分钟前
Vue3 指令详解
开发语言
_OP_CHEN18 分钟前
【从零开始的Qt开发指南】(二十三)Qt 界面优化之 QSS 实战指南:从入门到精通,让你的界面颜值飙升!
开发语言·c++·qt·前端开发·界面美化·qss·客户端开发
e***985721 分钟前
Java性能优化实战:从原理到案例
java·开发语言·性能优化
HellowAmy23 分钟前
我的C++规范 - 跳跃的对象
开发语言·c++·代码规范
lph00924 分钟前
QtMqtt 的编译与QT环境加载配置
开发语言·qt
焦糖玛奇朵婷41 分钟前
盲盒小程序:开发视角下的功能与体验
java·大数据·jvm·算法·小程序
崇山峻岭之间1 小时前
Matlab学习记录35
开发语言·学习·matlab
济6171 小时前
linux 系统移植(第六期)--Uboot移植(5)--bootcmd 和 bootargs 环境变量-- Ubuntu20.04
java·前端·javascript