1

I was wondering if you can define Lists in a similar format to:

List<int> blah = [5,7,8];

I already tried this and it didn't work, but is there a similar way of doing this? The reason I want to do this is because I am making a method with a List< List< string>> as an argument, and I wanted to be able to do this:

DoSomething( [ [1,2,3] , [1,2,3] , [1,2,3] ] );

Instead of doing:

List<List<string>> foo = new List<List<string>>();
//add each of the "[1,2,3]"s here
DoSomething(foo);

1 Answer 1

7

You can do it like this:

List<int> blah = new List<int> { 5,7,8 };

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

It is called a collection initializer.

Sign up to request clarification or add additional context in comments.

1 Comment

In the second example the type of the outer list should be List<List<int>>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.