是否有简洁的语法来初始化 C# 中的列表列表?
我试过了
new List<List<int>>{
{1,2,3},
{4,5},
{6,7,8,9}
};
但是我收到一个错误"方法'Add'没有重载需要 3 个参数"
编辑:我知道长语法
new List<List<int>>{
new List<int> {1,2,3},
new List<int> {4,5},
new List<int> {6,7,8,9}
};
我只是在寻找更精辟的东西。
不,您需要为每个new List<int>
:
var lists = new List<List<int>>() {
new List<int>{1,2,3},
new List<int>{4,5},
new List<int>{6,7,8,9}
};
通过在 C# 9.0/.NET 5 中引入目标类型的new
表达式,现在可以更简洁地创建List<List<T>>
,如下所示:
new List<List<int>>{
new () {1,2,3},
new () {4,5},
new () {6,7,8,9}
};
这也适用于字典初始值设定项,例如
new List<Dictionary<string, int>>{
new () {{"foo", 1}, {"bar", 2}}
};
或
new List<Dictionary<string, int>>{
new () {["foo"] = 1, ["bar"] = 2}
};