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


Comments (0)