2

Is there a concise syntax for intializing lists of lists in C#?

I tried

new List<List<int>>{
    {1,2,3},
    {4,5},
    {6,7,8,9}
};

But I get an error 'No overload for method 'Add' takes 3 arguments'


Edit: I know about the long syntax

 new List<List<int>>{
    new List<int>           {1,2,3},
    new List<int>           {4,5},
    new List<int>           {6,7,8,9}
};

I was just searching for something pithier.

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
  • Possible duplicate question: http://stackoverflow.com/questions/665299/are-2-dimensional-lists-possible-in-c –  Nov 27 '12 at 14:28
  • Not an answer but you could do something like this if you were using arrays: `new List { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } };` – Şafak Gür Mar 05 '14 at 08:27

2 Answers2

6

No, you need new List<int> for each:

var lists = new List<List<int>>() { 
    new List<int>{1,2,3},
    new List<int>{4,5},
    new List<int>{6,7,8,9}
};
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

With the introduction of target-typed new expressions in C# 9.0/.NET 5, you can now create a List<List<T>> more succinctly as follows:

new List<List<int>>{
    new () {1,2,3},
    new () {4,5},
    new () {6,7,8,9}
};

This works with dictionary initializers as well, e.g.

new List<Dictionary<string, int>>{
    new () {{"foo", 1}, {"bar", 2}}
};

or

new List<Dictionary<string, int>>{
    new () {["foo"] = 1, ["bar"] = 2}
};
dbc
  • 104,963
  • 20
  • 228
  • 340