C# 如何使用字典列表向字典添加值

C# 如何使用字典列表向字典添加值,c#,dictionary,C#,Dictionary,您好,我正在尝试向这个复杂对象添加值。我正在尝试使用JSON.Net将此对象转换为JSON Dictionary<string, List<Dictionary<string, int>>> MyList = new Dictionary<string, List<Dictionary<string, int>>>(); MyList.Add(“key1”,newlist对于它的价值,下面是一个示例循环,它展示了

您好,我正在尝试向这个复杂对象添加值。我正在尝试使用JSON.Net将此对象转换为JSON

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

MyList.Add(“key1”,newlist对于它的价值,下面是一个示例循环,它展示了如何使用和:

字典MyList=
新字典();
foreach(可枚举范围(1100))中的int i
{
var list=新列表();
foreach(可枚举范围(1100))中的int ii
添加(新字典(){“Item”+ii,ii});
MyList.Add(“项目”+i,列表);
}

尽管它看起来很复杂,但实际上非常简单:


您的词典采用
字符串的键和
列表的值。因此,要添加值,该值应始终为
列表
类型。如果您有
词典目录
,您可以通过

Dictionary<string, int> dictA = new Dictionary<string, int>();
dictA.Add("SomeString", 99);
Dictionary dictA=新字典();
添加(“SomeString”,99);
然后,要将此词典添加到您的
列表中
,请使用以下命令

List<Dictionary<string, int>> dictList = new List<Dictionary<string, int>>();
dictList.Add(dictA);
List dictList=newlist();
添加(dictA);
现在,您可以通过以下方式将其添加到
字典myList
对象中:

Dictionary<string, List<Dictionary<string, int>>> myList = 
    new Dictionary<string, List<Dictionary<string, int>>>();
myList.Add("SomeString", dictList);
字典myList=
新字典();
添加(“SomeString”,dictList);

我希望这能有所帮助。

请发布您尝试过的代码好吗?您遇到了什么问题?为什么您需要一个字典列表?可能没有更好、更可读的选项吗?只需从外部开始,以您的方式进入。向外部集合添加一个项目,在其中创建一个低一级的集合,然后执行以下操作ame为下一个级别,然后您可以将项目添加到最低级别。很抱歉,这是我第一次在这里提出问题。以后我会更详细地描述我的问题。谢谢大家。什么不起作用?您的代码是正确的(前提是您已将列表对象添加到“Dictionary”键
Dictionary<string, int> dictA = new Dictionary<string, int>();
dictA.Add("SomeString", 99);
List<Dictionary<string, int>> dictList = new List<Dictionary<string, int>>();
dictList.Add(dictA);
Dictionary<string, List<Dictionary<string, int>>> myList = 
    new Dictionary<string, List<Dictionary<string, int>>>();
myList.Add("SomeString", dictList);