填充具有嵌套列表作为值的字典的正确语法是什么

本文关键字:字典 是什么 语法 嵌套 列表 填充 | 更新日期: 2023-09-27 18:37:14

我是C#的新手,我正在尝试定义一个具有以下内容的字典:

作为键:

一个字符串


作为值:

a 字符串列表列表。


我能想到的(不完全确定它是否正确?)是这样的:

var peopleWithManyAddresses = new Dictionary<string, List<List<string>>> {};


现在,如果以上是正确的,我想知道如何填充一项peopleWithManyAddresses

Intellisense告诉我,以下内容仅在"卢卡斯"之前是正确的:

peopleWithManyAddresses.Add("Lucas", { {"first", "address"}, {"second", "address"} });

它的正确语法是什么?

附言我知道我可以使用一个类,但出于学习目的,我现在想这样做。

填充具有嵌套列表作为值的字典的正确语法是什么

若要初始化List<List<string>>对象,必须使用 new List<List<string>> { ... } 语法。要初始化每个子列表,您必须使用类似的语法,即 new List<string> {... } .下面是一个示例:

var peopleWithManyAddresses = new Dictionary<string, List<List<string>>>();
peopleWithManyAddresses.Add("Lucas", new List<List<string>>
{
    new List<string> { "first", "address" },
    new List<string> { "second", "address" }
});

您的初始化语句是正确的。

使用 C# 6.0,可以使用以下语法填充一个项:

var dict = new Dictionary<string, List<List<string>>>
{
    ["Lucas"] = new[]
    {
        new[] { "first", "address" }.ToList(),
        new[] { "second", "address" }.ToList(),
    }.ToList()
};

可以使用以下内容填充两个项目:

var dict = new Dictionary<string, List<List<string>>>
{
    ["Lucas"] = new[]
    {
        new[] { "first", "address" }.ToList(),
        new[] { "second", "address" }.ToList(),
    }.ToList(),
    ["Dan"] = new[]
    {
        new[] { "third", "phone" }.ToList(),
        new[] { "fourth", "phene" }.ToList(),
    }.ToList(),
};

如果以后要添加更多数据,可以执行以下操作:

dict["Bob"] = new[]
{
    new[] { "fifth", "mailing" }.ToList(),
    new[] { "sixth", "mailing" }.ToList(),
}.ToList();

首先我创建与Dictionary分开List

List<string> someList = new List<string<();
var otherList = new List<List<string>>();
var peopleWithManyAddresses = new Dictionary<string, List<List<string>>> {};

首先在某个列表中添加字符串

someList.Add("first");
someList.Add("addresss");

然后添加其他列表:

otherList.Add(someList);

现在创建新的字符串列表:

var thirdList = new List<string>();
thirdList.Add("second");
thirdList.Add("addresss");

并在其他列表中添加最后一个字符串列表并添加到字典中

otherList.Add(thirdList);
peopleWithManyAddresses.Add("Lucas", otherList);