Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToCharArray equivalent for List<string>

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?

like image 327
Johnado Avatar asked Nov 23 '14 03:11

Johnado


3 Answers

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()));
like image 165
Guffa Avatar answered Oct 17 '22 19:10

Guffa


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()));
like image 35
Stacked Avatar answered Oct 17 '22 18:10

Stacked


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

like image 38
mikebridge Avatar answered Oct 17 '22 18:10

mikebridge