Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<char> to List<string> in c#?

Tags:

c#

list

split

I have text. for example string text = "COMPUTER"
And I want to split it into characters, to keep every character as string.
If there were any delimiter I can use text.Split(delimiter).
But there is not any delimiter, I convert it to char array with
text.ToCharArray().toList().
And after that I get List<char>. But I need List<string>.
So How can I convert List<char> to List<string>.

like image 869
namco Avatar asked Jan 16 '15 06:01

namco


4 Answers

Just iterate over the collection of characters, and convert each to a string:

var result = input.ToCharArray().Select(c => c.ToString()).ToList();

Or shorter (and more efficient, since we're not creating an extra array in between):

var result = input.Select(c => c.ToString()).ToList();
like image 78
Grant Winney Avatar answered Oct 17 '22 09:10

Grant Winney


try this

   var result = input.Select(c => c.ToString()).ToList();
like image 2
varsha Avatar answered Oct 17 '22 08:10

varsha


Try following

string text = "COMPUTER"
var listOfChars = text.Select(x=>new String(new char[]{x})).ToArray()
like image 1
Tilak Avatar answered Oct 17 '22 09:10

Tilak


Use the fact that a string is internally already very close to an char[]

Approach without LINQ:

List<string> list = new List<string();
for(int i = 0; i < s.Length; i++)
    list.Add(s[i].ToString());
like image 1
DrKoch Avatar answered Oct 17 '22 08:10

DrKoch