List.AddRange inline declaration
Asked Answered
B

4

8

This may seem an easy question, but not to me, also a search has led to nothing. Up until now the only .net programming I have done is with Delphi Prism. With Prism I can do things like:

var l := new List<String>(['A','B','C']);

or

var l := new List<String>;
l.AddRange(['A','B','C'];

but can I do a similar thing in C#, or do I have to do it like:

var a = new String[] {"A","B","C"};
var l = new List<String>(a);
Bombazine answered 26/3, 2010 at 6:33 Comment(0)
D
24
 var l=new List<String>() {"A","B","C"};  

this will work

Droit answered 26/3, 2010 at 6:37 Comment(1)
Following recent revisions to the C# language, you would drop the (). The current syntax is --- var l = new List<string> {"A","B","C"};Knavish
A
6

collection initializer:

var list = new List<string>
{
    "A",
    "B",
    "C"
};

or correct ctor (mixed with collection initializer):

var list = new List<string>(new [] { "A", "B", "C" });
  • msdn for ctor infos
  • msdn for collection initializer
Ameeameer answered 26/3, 2010 at 6:36 Comment(0)
H
1

You can use Collection Initializers to achieve desired result.

Henryhenryetta answered 26/3, 2010 at 6:36 Comment(0)
P
0

As mentioned above, use collection initializers. In addition, if you are looking to convert from string[] to List , you can use the ToList() extension method in the System.Linq namespace like so:

string[] s = { "3", "4", "4"};
List<string> z = s.ToList();
Proscribe answered 26/3, 2010 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.