ToCharArray equivalent for List<string>

32.2k Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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

Here's one way

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

If you want the result as a List<char>, str.ToList() will work.

0
On

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