2009-11-05 8 views

Odpowiedz

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

Właśnie uświadomiłem sobie chcesz string [], a nie ciąg:

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

Nasty. Ale działa ...

+1

To nie tworzy napisu [], jak chciał Edward. –

1

Wystarczy wybrać ciąg zamiast znaku Char dla każdego z nielicznych liter.

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

Należy zauważyć, że wystarczy to zrobić w wywołaniu String.Join - z tym kodem wywołanie Count() kończy się konwersją każdego znaku na ciąg bezsensownie. (Możesz też wywołać ToList, aby raz obliczyć wyniki.) –

+0

Masz rację, nie myślałeś o wywołaniu .Count(). Najbardziej optymalnym rozwiązaniem byłoby dodanie .ToArray() przed Console.WriteLine następnie ;-) –

3

Myślę, że chcesz:

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

Wszystko robiłem to wezwanie Select(x => x.ToString()) na nonLetters w zaproszeniu string.join. Wydaje się działać.

5

Jeśli nie właściwie dbać o używaniu string.join ale chcą tylko wynik, używając nowy ciąg znaków (char []) to najprostsza zmiana:

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

ale dla przykładu jest bardziej efektywne, jeśli robisz to w ten sposób:

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

powodem jest to bardziej efektywne jest to, że drugi przykład iteracje swój gdzie iterator dwukrotnie: raz dla Count() połączenia, a drugi raz f lub wywołanie ToArray().

0

Z .NET 4 you have another overload dla łączenia. Tak proste, jak:

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

Zapisuje wam innego Select i ToArray część. Więc powinno być nieco bardziej wydajne. ToString jest wywoływany wewnętrznie.

Powiązane problemy