1

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
  • 126,394
  • 80
  • 383
  • 450
  • 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

1 Answers1

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
  • 429,027
  • 67
  • 649
  • 891