Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a hardcoded List? [duplicate]

Tags:

c#

.net

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 :)

like image 510
MrM Avatar asked Aug 31 '11 19:08

MrM


3 Answers

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");
like image 186
dlev Avatar answered Oct 26 '22 02:10

dlev


You can initialize a list with data like so:

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

like image 33
Chris Avatar answered Oct 26 '22 00:10

Chris


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"} ); 
like image 30
Brian Avatar answered Oct 26 '22 02:10

Brian