How to convert string to list in C#
By FoxLearn 12/20/2024 1:15:26 AM 27
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#
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 BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#
- Dictionary with multiple values per key in C#
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024