使用 C#12 集合表达式初始化 List<List>> 的语法是什么?

What's the syntax for using C#12 collection expressions to initialise a List<List>>?

提问人:stuartd 提问时间:11/17/2023 最后编辑:Guru Stronstuartd 更新时间:11/18/2023 访问量:158

问:

假设我有这样的代码(或任何类型的锯齿状结构):

var intListList = new List<List<int>> {
    new() { 1, 2, 3 }
};

我想在这里使用集合表达式。Resharper (EAP) 建议:

var intListList = new List<List<int>> {
    [1, 2, 3]
};

但这并不能编译。

这一定是可能的!语法是什么?

编辑:

还行。因此,从答案来看,而不是在表达式中声明类型:

// does not compile
var intListList = new List<List<int>> {
    [1, 2, 3]
};

该类型必须显式声明,并且没有:new()

// compiles!
List<List<int>> intListList = [[1, 2, 3]];
C net-8.0 C#-12.0

评论


答:

-1赞 Morten Bork 11/17/2023 #1

这是以所需语法初始化列表列表的正确方法。

 List<List<int>> list = new List<List<int>>()
 {
     new List<int>()
     {
         1, 2, 3
     }
 };

主要问题是,您没有初始化列表中包含 3 个值的列表。

我觉得很奇怪,Resharper 建议您尝试将列表初始化为数组?但这行不通。

如果需要多个列表示例:

List<List<int>> list = new List<List<int>>()
            {
                new List<int>()
                {
                    1, 2, 3
                },
                new List<int>()
                {
                    4, 5, 6
                },
            };

评论

2赞 lordvlad30 11/17/2023
C#12 中的新功能允许请求的语法:docs
0赞 dbc 11/17/2023
C# 9 以来,目标类型的新 () 表达式就已经存在,因此无需为内部 .Querent 使用是正确的。new List<int>() { 1, 2, 3 }new() { 1, 2, 3 }
0赞 Morten Bork 11/22/2023
喜欢你指出这一点的事实,但 OP 明确指出代码不会编译......什么语法,可以解决他的问题,并使其编译?恢复到较旧的语法...。然而,我的答案被否决了......洛维尔 y
7赞 Wiktor Zychla 11/17/2023 #2

由于这被标记为 C#12,我相信您可能正在寻找

List<List<int>> list = [[1,2,3]];
4赞 Guru Stron 11/17/2023 #3

用于 C# 12 中的新增功能中的交错数组的语法:

// Create a jagged 2D array:
int[][] twoD = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

似乎也适用于列表:

List<List<int>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

在线演示