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"});
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.
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.
Check out C# 3.0's Collection Initializers.
var list = new List<string> { "test1", "test2", "test3" };
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" };
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.
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