Counting Occurrences in char array

With LINQ:

public static IEnumerable<string> GetCharCountPlaceholders(IEnumerable<char> chars, char placeholder="*", string charCountDelimiter = " - ")
{
    return chars
        .GroupBy(c => c)
        .OrderBy(g => g.Key)
        .Select(g => String.Format("{0}{1}{2}"
         , g.Key
         , charCountDelimiter
         , new String(placeholder, g.Count())));
}

You could call it for example in this way:

char[] chars = { 'c', 'e', 'e', 'e', 'a', 'q' };
string result = String.Join(Environment.NewLine, GetCharCountPlaceholders(chars));

a - *
c - *
e - ***
q - *

Leave a Comment