2009-11-05 26 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

相關問題