C# 如何转换IEnumerable<;char>;将字符串[]与字符串一起使用。是否加入?

C# 如何转换IEnumerable<;char>;将字符串[]与字符串一起使用。是否加入?,c#,string,C#,String,如何将IEnumerable“非字母”转换为string[],以便与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.

如何将
IEnumerable
“非字母”转换为
string[]
,以便与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[] result = nonLetters.Select(c => new string(new[] { c })).ToArray();

讨厌。但它是有效的…

只需为每个非字母选择一个字符串而不是一个字符

string[] foo = nonLetters.Select(c => c.ToString()).ToArray();
String() nonLetters = message.Where(x => !Char.IsLetter(x))
                             .Select(x => x.ToString())
                             .ToArray();
我想你想要:

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

我所做的就是对字符串中的非字母调用
Select(x=>x.ToString())
。Join调用。似乎有效。

如果您实际上不关心使用String.Join但只想要结果,则使用新字符串(char[])是最简单的更改:

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()));
但就你的例子而言,如果你这样做,效率会更高:

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);
这更有效的原因是另一个示例将您的where迭代器迭代两次:一次用于Count()调用,另一次用于ToArray()调用。

使用for Join。简单到:

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

为您保存另一个
Select
ToArray
零件。所以效率应该稍微高一点。。
ToString
是在内部调用的。

这不会按照Edward的请求生成字符串[]。请注意,您只需要在对string.Join的调用中执行此操作-使用此代码,Count()调用将无意义地将每个字符转换为字符串。(或者,您可以调用ToList只计算一次结果。)您是对的,没有想到.Count()调用。最好的解决方案是在Console.WriteLine之前添加.ToArray(),然后;-)
var nonLettersJoined = string.Join(", ", message.Where(x => char.IsLetter(x)));