ToCharArray equivalent for List<string>

Johnado picture Johnado · Nov 23, 2014 · Viewed 28.5k times · Source

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?

Answer

Guffa picture Guffa · Nov 23, 2014

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()));