Convert comma separated string into a List in C#
This post will discuss how to convert a comma-separated string into a list in C#.
To convert a delimited string to a sequence of strings in C#, you can use the String.Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method. You need to include the System.Linq namespace to access the ToList() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { string s = "red,blue,green"; List<string> tokens = s.Split(',').ToList(); Console.WriteLine(String.Join(", ", tokens)); // red, blue, green } } |
Alternately, you can use the List<T> constructor to convert the string[] into a List<String>. This does not require LINQ.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { string s = "red,blue,green"; List<string> tokens = new List<string>(s.Split(',')); Console.WriteLine(String.Join(", ", tokens)); // red, blue, green } } |
The above solution returns a list of strings. If you need to convert the list of strings to another data type, say integer, you can use LINQ’s Select() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { string s = "1,2,3"; List<int> tokens = s.Split(',').Select(int.Parse).ToList(); Console.WriteLine(String.Join(", ", tokens)); // 1, 2, 3 } } |
If you don’t want to use LINQ, try using the Array.ConvertAll() method for converting an array to a list of a different type. This translates to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { string s = "1,2,3"; List<int> tokens = new List<int>(Array.ConvertAll(s.Split(','), int.Parse)); Console.WriteLine(String.Join(", ", tokens)); // 1, 2, 3 } } |
That’s all about converting a comma-separated string into a List 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 :)