2009-11-05 125 views

回答

12
string[] foo = nonLetters.Select(c => c.ToString()).ToArray(); 
2
string result = new string(nonLetters.ToArray()); //convert to a string 

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

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

讨厌。但它的工作原理...

+1

这不会像Edward要求的那样产生一个字符串[]。 – 2009-11-05 14:56:09

1

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

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

请注意,您只需要在调用String.Join时执行此操作 - 通过此代码,Count()调用将最终将每个字符无意义地转换为字符串。 (或者,你可以调用ToList来只计算一次结果。) – 2009-11-05 15:01:38

+0

你是对的,没有想到.Count()调用。最优化的解决方案是在Console.WriteLine之前添加.ToArray();然后 – 2009-11-05 15:35:11

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())。似乎工作。

5

如果你不真正关心使用的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); 

的原因,这是更有效的是,其他示例循环您其中迭代两次:一次是对count()调用,其他时间F或ToArray()调用。

0

With .NET 4 you have another overload for Join。就这么简单:

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

节省您的另一SelectToArray一部分。所以应该更有效率..内部调用ToString

相关问题