Phorce Phorce - 1 month ago 9
C# Question

LINQ C# Selecting characters from string

let me try and explain this the best I can.

Basically, I have a string that I convert to a char array and then I use LINQ to select the different characters inside the char array and then order them by Descending but only catch the characters, not the punctuation marks etc.. Here is the code:

string inputString = "The black, and, white cat";
var something = inputString.ToCharArray();
var txtEntitites = something.GroupBy(c => c)
.OrderByDescending(g => g.Count())
.Where(e => Char.IsLetter(e)).Select(t=> t.Key);


And the error message I get:


  • Error CS1502: The best overloaded method match for `char.IsLetter(char)' has some invalid arguments (CS1502)

  • Error CS1503: Argument
    #1' cannot convert
    System.Linq.IGrouping' expression to type `char' (CS1503)



Any ideas? Thanks :)

Answer

Try this:

string inputString = "The black, and, white cat"; 
var something = inputString.ToCharArray();  
var txtEntitites = something.GroupBy(c => c)
                            .OrderByDescending(g => g.Count())
                            .Where(e => Char.IsLetter(e.Key))
                            .Select(t=> t.Key);

Note the Char.IsLetter(e.Key))

Another idea is to rearrange your query:

varinputString = "The black, and, white cat"; 
var txtEntitites = inputString.GroupBy(c => c)
                              .OrderByDescending(g => g.Count())
                              .Select(t=> t.Key)
                              .Where(e => Char.IsLetter(e));

Also note you don't need the call to inputString.ToCharArray() since String is already an IEnumerable<Char>.