Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to create a list of values in C#?

Tags:

c#

list

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"});
like image 990
Piotr Czapla Avatar asked Apr 06 '09 21:04

Piotr Czapla


People also ask

How do you create a list of integers and assign value in C?

In C# 3, you can do: IList<string> l = new List<string> { "test1", "test2", "test3" }; This uses the new collection initializer syntax in C# 3. In C# 2, I would just use your second option.

What is list in C sharp?

Lists in C# are very similar to lists in Java. A list is an object which holds variables in a specific order. The type of variable that the list can store is defined using the generic syntax. Here is an example of defining a list called numbers which holds integers.


3 Answers

Check out C# 3.0's Collection Initializers.

var list = new List<string> { "test1", "test2", "test3" };
like image 130
Neil Williams Avatar answered Oct 09 '22 03:10

Neil Williams


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" };
like image 27
Konrad Rudolph Avatar answered Oct 09 '22 05:10

Konrad Rudolph


In C# 3, you can do:

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

This uses the new collection initializer syntax in C# 3.

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

like image 11
Reed Copsey Avatar answered Oct 09 '22 05:10

Reed Copsey