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?

+3


source to share


3 answers


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

      

+6


source


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

      

+1


source


Here's one way

string data = "ABCDEFGHIJ1fFJKAL";
List<string> datalist = new List<string>();
datalist.AddRange(data.Select (d => d.ToString()));

      

0


source







All Articles