Method 1: Using Split Method
We can convert a string to a collection using the Split
method. This method splits a string into an array of substrings based on a specified delimiter.
using System;
class Program
{
static void Main()
{
string data = "red,blue,orange,white,vilot";
string[] colors = data.Split(',');
Console.WriteLine("String to Collection using Split Method:");
foreach (var color in colors)
{
Console.WriteLine(color);
}
Console.ReadKey();
}
}
Output:
String to Collection using Split Method:
red
blue
orange
white
vilot
In this example, the string "red,blue,orange,white,vilot" is split into an array of strings using the comma (,
) as the delimiter.
Method 2: Using LINQ
This LINQ allows for more complex operations on collections. Check the below program.
using System;
using System.Linq;
class Program
{
static void Main()
{
string data = "1,2,3,4,5";
var numbers = data.Split(',').Select(int.Parse).ToList();
Console.WriteLine("String to Collection using LINQ:");
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
Output:
String to Collection using LINQ:
1
2
3
4
5
This program converts a string of comma-separated numbers into a list of integers using LINQ's Select
method.
Comments (0)