Most Common Character

Given a string, return the character that is most commonly occurred in the string.

Using Dictionary

One way to find maximum number of characters is to create a new Dictionary<TKey, TValue> of integers, with character keys. Then iterate through all the characters, and for every character either add the character as a new key with a value of one to the dictionary or if the character has been already added, update the value and add one to it.

using System.Collections.Generic;

 public static (char, int) MaxChar(string str)
 {
     // Create a new dictionary of integers, with character keys.
     var dictionary = new Dictionary<char, int>();

     // Loop over all the characters.
     foreach (var c in str)
     {
         // If a key exists, update the value and add one to it.
         if (dictionary.ContainsKey(c))
         {
             dictionary[c] += 1;
         }
         else
         {
             // If a key does not exist, add a new key with value of one.
             dictionary.Add(c, 1);
         }
     }

     // Sort the dictionary descending based on the values.
     var (chr, count) = dictionary
         .OrderByDescending(x => x.Value)
         .First();
     return (chr, count);
 }
Modifying Implementation

Using ContainsKey() method followed by the indexer (Item[]) is not optimal because it duplicates lookup process. Therefore, We are going to change the above code by using TryGetValue() method. This method combines the functionality of the ContainsKey() method and the indexer.

using System.Collections.Generic;

 public static (char, int) MaxChar(string str)
 {
     var dictionary = new Dictionary<char, int>();

     foreach (var c in str)
     {
         if (!dictionary.TryGetValue(c, out var i))
         {
             dictionary.Add(c, 1);
         }
         else
         {
             dictionary[c] = ++i;
         }
     }

     var (chr, count) = dictionary
         .OrderByDescending(x => x.Value)
         .First();
     return (chr, count);
 }
LINQ Operators

Now let's look through the third implementation of maximum number of characters using LINQ operators. The basic overload to the GroupBy() method takes a lambda expression representing the key to create the groups for. In the following query the GroupBy() operator takes a string as input character sequence and groups them by each character. Then, the Select() operator projects the results into an anonymous type that contains the group key and number of items in each group. The OrderByDescending() sorts in reverse order the sequence by comparing the values and First() returns the top element in the sequence.

using System.Linq;

 public static (char, int) MaxChar(string str)
 {
     var result = str
         .GroupBy(c => c)
         .Select(x => new { Key = x.Key, Value = x.Count() })
         .OrderByDescending(x => x.Value)
         .First();
     return (result.Key, result.Value);
 }

You can download the source code on Github.