Split String to List in C#

Muhammad Maisam Abbas Mar 15, 2021
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#.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

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.

LinkedIn

Related Article - Csharp String

Related Article - Csharp List