How do you split a string to a List? I'm looking for the equivalent of ToCharArray but instead to make it a List.
string data = "ABCDEFGHIJ1fFJKAL";
List<string> datalist = new List<string>();
datalist.AddRange(new List<string>{"A","B","C"});
How do you convert data so it will be accepted by AddRange?
If you want a list of characters, then you would use a List<char>
rather than List<string>
, and then you don't have to do anything at all to the string. The AddRange
method takes an IEnumerable<char>
and the String
class happens to implement IEnumerable<char>
:
string data = "ABCDEFGHIJ1fFJKAL";
List<char> datalist = new List<char>();
datalist.AddRange(data);
If you want a List<string>
to hold the characters anyway, then you would need to convert each character to a string:
string data = "ABCDEFGHIJ1fFJKAL";
List<string> datalist = new List<string>();
datalist.AddRange(data.Select(c => c.ToString()));
Since the initialization of a new list instance accepts a collection whose elements will be copied to the new list, the answer of Guffa can be shortened to:
string data = "ABCDEFGHIJ1fFJKAL";
List<char> datalist = new List<char>(data);
And:
string data = "ABCDEFGHIJ1fFJKAL";
List<string> datalist = new List<string>(data.Select(c => c.ToString()));
If you want the result as a List<char>
, str.ToList()
will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With