Possible Duplicate:
Simplified Collection initialization
I have the string values, I just want to set them in a list. Something like -
List<string> tempList = List<string>();
tempList.Insert(0,"Name",1,"DOB",2,"Address");
I guess I am having a brain freeze :)
var tempList = new List<string> { "Name", "DOB", "Address" };
With the collection initializer syntax, you don't even need the explicit calls to Add() or Insert(). The compiler will put them there for you.
The above declaration is actually compiled down to:
List<string> tempList = new List<string>();
tempList.Add("Name");
tempList.Add("DOB");
tempList.Add("Address");
You can initialize a list with data like so:
var list = new List<string> { "foo", "bar", "baz" };
You can also use AddRange which would accomplish the same thing if the list already exists:
List<string> tempList = new List<string>();
tempList.AddRange( new string[] {"Name", "DOB", "Address"} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With