tags:

views:

634

answers:

5

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())
    );
+1  A: 
string result = new string(nonLetters.ToArray()); //convert to a string

I just realized you want a string[] and not a string:

string[] result = nonLetters.Select(c => new string(new[] { c })).ToArray();

Nasty. But it works...

ifwdev
This doesn't produce a string[] as Edward requested.
Rob van Groenewoud
+6  A: 
string[] foo = nonLetters.Select(c => c.ToString()).ToArray();
LukeH
+1  A: 

Just select a String instead of a Char for each of your non-letter.

String() nonLetters = message.Where(x => !Char.IsLetter(x))
                             .Select(x => x.ToString())
                             .ToArray();
Meta-Knight
Note that you only need to do that in the call to String.Join - with this code, the Count() call will end up converting each char to a string pointlessly. (Alternatively you could call ToList to only compute the results once.)
Jon Skeet
You're right, didn't think of the .Count() call. The most optimal solution would be to add the .ToArray() before the Console.WriteLine then ;-)
Meta-Knight
+2  A: 

I think you want:

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.Select(x => x.ToString()).ToArray())
    );

All I've done is call Select(x => x.ToString()) on nonLetters in the String.Join call. Seems to work.

Jon Skeet
A: 

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.

Ray Burns