In previous article, I have mentioned how to convert list to comma separated string in C#, but now in this article, I have mentioned how we can convert comma separated string to List in C# and array string into list using C# console application example.
Convert String to List using C#
First, we will split string by using "," as delimiter
Next, We can simply use List<T>
constructor (which accepts IEnumerable<T>
) which will take convert splitted string into List
So here is the complete code
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var names = "Ariana,Peter,John";
List<string> nameList = new List<string>(names.Split(','));
foreach(var name in nameList)
{
Console.WriteLine(name);
}
}
}
Output:
Ariana
Peter
John
Linq method (Using .ToList())
There is another method using Linq to convert string into list.
We can also simply use .ToList()
Linq method after splitting string using .Split()
using System;
using System.Collections.Generic;
using System.Linq; // add this
public class Program
{
public static void Main()
{
var names = "Ariana,Peter,John";
List<string> nameList = names.Split(',').ToList(); // .ToList() using System.Linq
foreach(var name in nameList)
{
Console.WriteLine(name);
}
}
}
Output is same as above.
Convert String Array to List using C#
Now, as you can see in above example, we were using string with "," as seperator, to convert it into an array
But if you are using srting array, then you can simply use .ToList()
linq method on an array to convert it into List.
using System;
using System.Collections.Generic;
using System.Linq; // add this
public class Program
{
public static void Main()
{
string [] array = { "Hello","World", "John", "Here"};
List<string> listItems = array.ToList();
foreach(var name in listItems)
{
Console.WriteLine(name);
}
}
}
and the output of above code will be
Hello
World
John
Here
That's it, hope it helps.
You may also like to read:
Visual Studio Code Intellisense (autocomplete) not working
How can I convert string to time in C#?
Useful Visual Studio Shortcuts (comment, remove comment, Collapse code etc )
Using Generics in C# (With Example)
File I/O in C# (Read, Write, Delete, Copy file using C#)
Object Oriented Programming (OOPS) concepts in c# with example