How to convert string to list in C#
By FoxLearn 2/7/2025 1:57:47 AM 614
In C#, you can convert a string to a list by following these steps.
If you want to break the string into individual characters and store them in a list, you can use the ToList()
method.
How to convert a string to a list of chars in C#?
string str = "Hello"; List<char> charList = str.ToList(); // Output the list of characters foreach (var c in charList) Console.WriteLine(c);
Output:
H e l l o
If you want to split the string into a list of substrings based on a delimiter, you can use the Split()
method.
For example, Convert a string into a list of substrings in C#
// to string list c# string str = "apple,banana,orange"; List<string> list = new List<string>(str.Split(',')); // Output the list of substrings foreach (var item in list) Console.WriteLine(item);
Output:
apple banana orange
If you want to convert the example below to a List<string>
delimited by commas, in one line
var names = "Brian,Joe,Chris";
You can write
List<string> result = names.Split(new char[] { ',' }).ToList();
or
List<string> result = names.Split(',').ToList();
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024