Initialize List in a single line in C#
This post will discuss how to initialize a List in a single line in C#.
We can initialize a list inline in C# using the new List<Type> { Value1, Value2, .., ValueN }; syntax. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> strings = new List<string> { "Blue", "Red", "Yellow" }; Console.WriteLine(String.Join(", ", strings)); // Blue, Red, Yellow } } |
The List<T> provides a constructor that initializes a new instance of the List<T> class containing elements copied from the specified collection. The following example demonstrates this by creating an array of strings and passing it to the List<T> constructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Collections.Generic; public class Example { public static void Main() { string[] colors = { "Blue", "Red", "Yellow" }; List<string> strings = new List<string>(colors); Console.WriteLine(String.Join(", ", strings)); // Blue, Red, Yellow } } |
We can do this in a single step by combining the list constructor with the array initializer syntax.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> strings = new List<string>(new string[] { "Blue", "Red", "Yellow" }); Console.WriteLine(String.Join(", ", strings)); // Blue, Red, Yellow } } |
That’s all about initializing a List in a single line in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)