Count distinct characters
suggest changeIf 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() });
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents