Skip to content

Count The Occurences Of Characters In A String Using LINQ

In a given string we are going to find the occurrences of each character using LINQ.

In the given string we will do group by, then we do select of element into a new object of Key-Value type. The key will the character and value will be the count of that character. As this will be a dictionary and there could be multiple characters hence we will do a foreach loop to fetch the character and their count. It will display the items in the order they are found in the given string. As we can see in the code we have taken care of the caps of the user input text hence it will not differentiate between the caps and non-caps letters.

In order to execute the code I’ve created a simple console application to print out the result.

Please find complete code below:

using System; 
using System.Collections; 
using System.Linq; 

namespace PracticeConsole 
{ 
   class Program 
   { 
      static void Main(string[] args) 
      { 
         Console.WriteLine("Please enter a text and then hit enter:"); 
         string checkOccurencesString = Console.ReadLine(); 
         var dictionaryObjectResult= checkOccurencesString.ToLower().GroupBy(x => x).Select(x => new { Key = x.Key.ToString(), Value = x.Count() }).ToDictionary(t => t.Key, t => t.Value); 
         foreach (var item in dictionaryObjectResult) 
         { 
            Console.WriteLine(item.Key + " " + item.Value); 
         } 
         Console.ReadLine(); 
      } 
   } 
}

Result: