Convert Strings to Lists in C#
We will see a simple approach using the Split()
method. This method is used to split a string into substrings based on a specified delimiter and returns an array of the substrings. We can then easily convert this array into a list using the List<T>
constructor.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string data = "apple,kiwi,grapes";
char delimiter = ',';
// Split the string into substrings
string[] substrings = data.Split(delimiter);
// Convert array to list
List<string> myList = new List<string>(substrings);
// Output the list
foreach (string item in myList)
{
Console.WriteLine(item);
}
}
}
Output:
apple
kiwi
grapes
This method involves using LINQ (Language-Integrated Query) to split the string and convert it into a list.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
string data = "kiwi,orange,grapes";
char delimiter = ',';
// Split the string and convert to list using LINQ
List<string> myList = data.Split(delimiter).ToList();
// Output the list
foreach (string item in myList)
{
Console.WriteLine(item);
}
}
}
Output:
kiwi
orange
grapes
We can also use the Split()
method to convert strings to lists. This allows you to specify multiple delimiters or more complex splitting criteria.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string data = "apple,kiwi;orange";
char[] delimiters = { ',', ';' };
// Split the string using multiple delimiters
string[] substrings = data.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
// Convert array to list
List<string> myList = new List<string>(substrings);
// Output the list
foreach (string item in myList)
{
Console.WriteLine(item);
}
}
}
Output:
apple
kiwi
orange
Comments (1)
This blog provides a clear step-by-step approach, crucial for both my learning journey and finding reliable assignment.