Phorce
Phorce

Reputation: 2664

LINQ C# Selecting characters from string

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:

Any ideas? Thanks :)

Upvotes: 7

Views: 29768

Answers (4)

codekaizen
codekaizen

Reputation: 27419

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:

var inputString = "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>.

Upvotes: 9

Den
Den

Reputation: 51

List<char> charArray = (
      from c in inputString
      where c >= 'A' && c <= 'z'
      orderby c
      select c
   ).Distinct()
   .ToList();

Upvotes: 2

Jeff Mercado
Jeff Mercado

Reputation: 134841

In your where clause, e in that context is your grouping, not the character. If you want to check if the character is a letter, you should be testing your key.

//...
.Where(g => Char.IsLetter(g.Key))

Upvotes: 2

Malgaur
Malgaur

Reputation: 1850

I think this is what you are looking for

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

Upvotes: 1

Related Questions