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#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp String

  • Convert a String to Boolean in C#
  • Related Article - Csharp List

  • C# Convert String to Enum
  • Generate Random Alphanumeric Strings in C#