Edward Tanguay
Edward Tanguay

Reputation: 193322

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

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())
    );

Upvotes: 7

Views: 8637

Answers (6)

nawfal
nawfal

Reputation: 73193

With .NET 4 you have another overload for Join. As simple as:

var nonLettersJoined = string.Join(", ", message.Where(x => char.IsLetter(x)));

Saves you another Select and ToArray part. So should be slightly more efficient.. The ToString is called internally.

Upvotes: 0

Ray Burns
Ray Burns

Reputation: 62929

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.

Upvotes: 5

Meta-Knight
Meta-Knight

Reputation: 17875

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();

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500953

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.

Upvotes: 3

kwcto
kwcto

Reputation: 3504

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...

Upvotes: 2

LukeH
LukeH

Reputation: 269428

string[] foo = nonLetters.Select(c => c.ToString()).ToArray();

Upvotes: 12

Related Questions