Split a delimited string into a List in C#
This post will discuss how to split a delimited string into a List in C#.
In LINQ, you can use the String.Split() method to break a delimited string into substrings based on the specified delimiter. To convert the resultant string array into a list, you may call 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 = "1,2,3,4,5"; List<string> result = s?.Split(',').ToList(); Console.WriteLine(String.Join(", ", result)); // 1, 2, 3, 4, 5 } } |
The above solution returns a list of strings. To convert each string into an integer, invoke the Enumerable.Select() method before 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 = "1,2,3,4,5"; List<int> result = s?.Split(',').Select(Int32.Parse).ToList(); Console.WriteLine(String.Join(", ", result)); // 1, 2, 3, 4, 5 } } |
Another option to convert an array to a list of a different type is using the Array.ConvertAll() method. The following code example demonstrates its usage. Note that the solution uses a List constructor for converting the array into a list:
|
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,4,5"; List<int> result = new List<int>(Array.ConvertAll(s?.Split(','), int.Parse)); Console.WriteLine(String.Join(", ", result)); // 1, 2, 3, 4, 5 } } |
That’s all about splitting a delimited 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 :)