Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use collection expressions for a List<List>>?

Say I have code like this:

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

I’d like to use a collection expression here. Resharper (EAP) suggests this:

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

But that doesn’t compile:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error CS1003: Syntax error, '=' expected
error CS1525: Invalid expression term ','

Is this possible? If so, what’s the syntax?

>Solution :

The syntax used for the jagged arrays from the What’s new in C# 12:

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

Seems to work for lists also:

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

Online Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading