user3770093 user3770093 - 2 months ago 8
C# Question

Count All Character Occurrences in a String C#

What is the best way to dynamically count each character occurrence in C#?

given

string sample = "Foe Doe";


it should output something like

f = 1
o = 2
e = 2
d = 1


counting a single character would be easy but in my exam this was a bit tricky, I could only imagine a solution to get all unique characters -> then store it in a collection(preferably an array) then a nested for loop for the array and the string.

Is there a better solution than this?

Answer

Use LINQ

sample.GroupBy(c => c).Select(c => new { Char = c.Key, Count = c.Count()});