Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert IEnumerable<char> to string[] so I can use it with String.Join?

Tags:

string

c#

How can I convert the IEnumerable<char> "nonLetters" to a string[] so that I can use it with String.Join?

string message = "This is a test message.";

var nonLetters = message.Where(x => !Char.IsLetter(x));

Console.WriteLine("There are {0} non-characters in \"{1}\" and they are: {2}", 
    nonLetters.Count(), 
    message,
    String.Join(", ", nonLetters.ToArray())
    );
like image 742
Edward Tanguay Avatar asked Nov 05 '09 14:11

Edward Tanguay


2 Answers

string[] foo = nonLetters.Select(c => c.ToString()).ToArray();
like image 193
LukeH Avatar answered Sep 20 '22 15:09

LukeH


If you don't actually care about using String.Join but only want the result, using new string(char[]) is the simplest change:

string message = "This is a test message.";
var nonLetters = message.Where(x => !Char.IsLetter(x));
Console.WriteLine("There are {0} non-characters in \"{1}\" and they are: {2}",
     nonLetters.Count(),
     message,
     new string(nonLetters.ToArray()));

but for your example it is more efficient if you do it this way:

string message = "This is a test message.";
string nonLetters = new string(message.Where(x => !Char.IsLetter(x)).ToArray());
Console.WriteLine("There are {0} non-characters in \"{1}\" and they are: {2}",
     nonLetters.Length,
     message,
     nonLetters);

The reason this is more efficient is that the other example iterates your where iterator twice: Once for the Count() call and the other time for the ToArray() call.

like image 45
Ray Burns Avatar answered Sep 22 '22 15:09

Ray Burns