How can I initialize a C # list on the same line that I declare. (Example IEnumerable String Collection)

I am writing my test code and I do not want to write wo:

List<string> nameslist = new List<string>(); nameslist.Add("one"); nameslist.Add("two"); nameslist.Add("three"); 

I would like to write

 List<string> nameslist = new List<string>({"one", "two", "three"}); 

However, {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialize this in a single line using the IEnumerable Collection line ??

+95
collections list initialization c #
Dec 14 '10 at
source share
7 answers
 var list = new List<string> { "One", "Two", "Three" }; 

Essentially, the syntax is:

 new List<Type> { Instance1, Instance2, Instance3 }; 

What does the compiler translate as

 List<string> list = new List<string>(); list.Add("One"); list.Add("Two"); list.Add("Three"); 
+155
Dec 14 '10 at 10:33
source share

Change the code to

 List<string> nameslist = new List<string> {"one", "two", "three"}; 

or

 List<string> nameslist = new List<string>(new[] {"one", "two", "three"}); 
+16
Dec 14 '10 at 10:32
source share

Just lose the bracket:

 var nameslist = new List<string> { "one", "two", "three" }; 
+6
Dec 14 '10 at 10:36
source share
 List<string> nameslist = new List<string> {"one", "two", "three"} ? 
+3
Dec 14 '10 at 10:32
source share

Remove parentheses:

 List<string> nameslist = new List<string> {"one", "two", "three"}; 
+3
Dec 14 '10 at 10:33
source share

It depends on which version of C # you are using, starting with version 3.0, which you can use ...

 List<string> nameslist = new List<string> { "one", "two", "three" }; 
+3
Dec 14 '10 at 10:34
source share

I think this will work for int, long and string values.

 List<int> list = new List<int>(new int[]{ 2, 3, 7 }); var animals = new List<string>() { "bird", "dog" }; 
0
Sep 03 '19 at 15:10
source share



All Articles