user3770093 user3770093 - 1 year ago 127
C# Question

Count All Character Occurrences in a String C#

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


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 Source


sample.GroupBy(c => c).Select(c => new { Char = c.Key, Count = c.Count()});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download