tags:

views:

557

answers:

8

I'm looking for a quick way to create a list of values in C#. In Java I frequently use the snippet below:

List<String> l = Arrays.asList("test1","test2","test3");

Is there any equivalent in C# apart from the obvious one below?

IList<string> l = new List<string>(new string[] {"test1","test2","test3"});
A: 

what is wrong with your suggestion in C#?

ooo
+10  A: 

Check out C# 3.0's Collection Initializers.

var list = new List<string> { "test1", "test2", "test3" };
Neil Williams
+1  A: 
IList<string> list = new List<string> {"test1", "test2", "test3"}
Matt Grande
+2  A: 

In C# 3, you can do:

IList<string> l = new List<string> { "test1", "test2", "test3" };

This uses the new object initializer in C# 3.

In C# 2, I would just use your second option.

Reed Copsey
+1  A: 

You can simplify that line of code slightly in C# by using a collection initialiser.

var lst = new List<string> {"test1","test2","test3"};
Noldorin
A: 

You can drop the new string[] part:

List<string> values = new List<string> { "one", "two", "three" };
John Rasch
+3  A: 

If you're looking to reduce clutter, consider

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

This uses two features of C# 3.0: type inference (the var keyword) and the collection initializer for lists.

Alternatively, if you can make do with an array, this is even shorter (by a small amount):

var arr = new [] { "foo", "bar" };
Konrad Rudolph
A: 

A list of values quickly? Or even a list of objects!

I am just a beginner at the C# language but I like using

  • Hashtable
  • Arraylist
  • Datatable
  • Datasets

etc.

There's just too many ways to store items

Brad