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

相关推荐
天若有情6734 分钟前
从零搭建校园二手交易系统:Vue2 + SpringBoot 4.x 全栈实战
java·spring boot·后端
学逆向的4 分钟前
C 浮点数e(科学计数法)
c语言·开发语言·网络安全
lexiangqicheng13 分钟前
1,自定义表单通俗理解-PC设计APP渲染
java·前端·javascript
quantdash_cc15 分钟前
如何给自己的量化策略增加独立数据层?从数据获取到策略解耦的 Python 实践
开发语言·python·数据分析·量化交易·股票数据·quantdash
NeoGressAI外贸数字化16 分钟前
外贸独立站3类页面合格度,怎么用脚本一次跑完
开发语言·python
南极企鹅22 分钟前
生产环境gc文件分析
java·jvm·算法
Wang's Blog23 分钟前
Java 项目实战: 交友项目 - 前后端分离的工程实践
java·spring cloud·架构
X北辰北27 分钟前
C++ 进阶第二阶段总结|STL容器全家桶、迭代器失效、STL算法、序列化入门(工程必备)
开发语言·c++·算法
溪语流沙31 分钟前
面试加分项!Manacher:O(n)求最长回文子串的对称之美
java·python·leetcode·面试·职场和发展