Split String to List in C#

This tutorial will discuss methods to split a string variable into a list of strings in C#.
Split a String Variable to a List of Strings With the String.Split()
Method in C#
The String.Split()
method splits a string variable based on the given separator in C#. The String.Split()
splits the main string into multiple sub-strings and returns them in the form of a string array. The array of strings returned by the String.Split()
method can be converted into a list by using the ToList()
function of Linq in C#. The following code example shows us how we can split a string variable into a list of strings based on a separator with the String.Split()
and ToList()
functions in C#.
using System;
using System.Collections.Generic;
using System.Linq;
namespace split_string_to_list
{
class Program
{
static void Main(string[] args)
{
string split = "this, needs, to, split";
List<string> list = new List<string>();
list = split.Split(',').ToList();
foreach(var l in list)
{
Console.WriteLine(l);
}
}
}
}
Output:
this
needs
to
split
In the above code, we split the string variable split
based on the separator ,
with the split.Split(',')
function. The resultant array was converted to the list of strings list
with the ToList()
function in C#.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedInRelated Article - Csharp String
- C# Convert String to Enum
- C# Convert Int to String
- Use Strings in Switch Statement in C#
- Convert a String to Boolean in C#
- Convert a String to Float in C#
- Convert a String to a Byte Array in C#
Related Article - Csharp List
- Convert an IEnumerable to a List in C#
- C# Remove Item From List
- C# Join Two Lists Together
- Get the First Object From List<Object> Using LINQ
- Find Duplicates in a List in C#
- The AddRange Function for List in C#