TechieClues TechieClues
Updated date Jan 19, 2023
In this blog, we will learn how to convert a comma-separated string into a List in C#
  • 13.7k
  • 0
  • 0

We can easily convert a comma-separated string into a List in C# using String.Split() method.

In the below code snippet, String.Split() method splits a comma-separated string into substrings based on the characters in an array, then you can convert the arrays into a list as shown below. You have to add the reference System.Linq for the method ToList().

using System;
using System.Linq;
using System.Collections.Generic;

namespace ConvertCommSepStringToList
{
    class Program
    {
        static void Main()
        {
            // Comma-seperated String
            string colorStr = "Red,Blue,White,Pink,Yellow";

            // Split a string into substrings based on the ","
            List<string> colors = colorStr.Split(',').ToList();

            // Display the element
            foreach (string color in colors)
                Console.WriteLine(color);            
            Console.ReadKey();
        }
    }
}

Output:

Red
Blue
White
Pink
Yellow

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!