如何将IEnumerable <char>转换为string [],以便我可以将它与String.Join一起使用?</char>

时间:2009-11-05 14:50:21

标签: c# string

如何将IEnumerable<char>“nonLetters”转换为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())
    );

6 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:5)

如果你实际上并不关心使用String.Join但只想要结果,那么使用 new string(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()调用。

答案 2 :(得分:3)

我想你想要:

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

我所做的就是在String.Join调用中的nonLetters上调用Select(x => x.ToString())。似乎工作。

答案 3 :(得分:2)

string result = new string(nonLetters.ToArray()); //convert to a string

我刚刚意识到你想要一个字符串[]而不是一个字符串:

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

讨厌。但它有效......

答案 4 :(得分:1)

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

String() nonLetters = message.Where(x => !Char.IsLetter(x))
                             .Select(x => x.ToString())
                             .ToArray();

答案 5 :(得分:0)

使用.NET 4 you have another overload加入。简单如下:

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

为您保存另一个SelectToArray部分。所以应该稍微提高效率..内部调用ToString