How to create a hard list?

Possible duplicate:
Simplified collection initialization

I have string values, I just want to set them in a list. Sort of -

List<string> tempList = List<string>();
tempList.Insert(0,"Name",1,"DOB",2,"Address");

I think I have a brain freeze :)

+5
source share
3 answers
var tempList = new List<string> { "Name", "DOB", "Address" };

With the collection initializer syntax, you don't even need explicit calls to Add()or Insert(). The compiler will post them for you.

The above declaration is actually compiled to:

List<string> tempList = new List<string>();
tempList.Add("Name");
tempList.Add("DOB");
tempList.Add("Address");
+20
source

You can initialize the list with this data:

var list = new List<string> { "foo", "bar", "baz" };

+4
source

AddRange, , :

List<string> tempList = new List<string>();
tempList.AddRange( new string[] {"Name", "DOB", "Address"} ); 
0

All Articles