ToCharArray equivalent for List <string>
How do you split a string into a list? I'm looking for the equivalent of ToCharArray, but I'll make it a List instead.
string data = "ABCDEFGHIJ1fFJKAL";
List<string> datalist = new List<string>();
datalist.AddRange(new List<string>{"A","B","C"});
How do you convert the data to be accepted using AddRange?
source to share
If you want a list of characters, you should use List<char>
, not List<string>
, and then you don't need to do anything with the string. The method AddRange
accepts IEnumerable<char>
, and the class String
implements IEnumerable<char>
:
string data = "ABCDEFGHIJ1fFJKAL";
List<char> datalist = new List<char>();
datalist.AddRange(data);
If you want to List<string>
preserve characters anyway, you will need to convert each character to a string:
string data = "ABCDEFGHIJ1fFJKAL";
List<string> datalist = new List<string>();
datalist.AddRange(data.Select(c => c.ToString()));
source to share
Since the initialization of a new instance of a list takes a collection, whose elements will be copied to the new list, Guffa's answer 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()));
source to share