Count distinct characters

suggest change

If you need to count distinct characters, for the reasons explained in the Remarks section of Strings, you can’t simply use the Length property. Length is the number of System.Char values, which are UTF-16 code units, not Unicode code points or graphemes. text.Distinct().Count() is wrong for the same reason. Correct code:

int distinctCharactersCount = text.EnumerateCharacters().Count();

One step further is to count occurrences of each character. If performance is not an issue, you may do it like this (in this example, regardless of case):

var frequencies = text.EnumerateCharacters()
    .GroupBy(x => x, StringComparer.CurrentCultureIgnoreCase)
    .Select(x => new { Character = x.Key, Count = x.Count() });

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents