开发者

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

开发者 https://www.devze.com 2022-12-10 03:38 出处:网络
How can I convert the IEnumerable<char> \"nonLetters\" to a string[] so 开发者_JAVA百科that I can use it with String.Join?

How can I convert the IEnumerable<char> "nonLetters" to a string[] so 开发者_JAVA百科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())
    );


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


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.


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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消