7

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?

Johnado
  • 73
  • 1
  • 1
  • 3

4 Answers4

16

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()));
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
5

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()));
Stacked
  • 6,892
  • 7
  • 57
  • 73
1

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

mikebridge
  • 4,209
  • 2
  • 40
  • 50
0

Here's one way

string data = "ABCDEFGHIJ1fFJKAL";
List<string> datalist = new List<string>();
datalist.AddRange(data.Select (d => d.ToString()));
Ross Presser
  • 6,027
  • 1
  • 34
  • 66