Count repetitive words in string array in C#

Rahul Patil 46 Reputation points
2025-04-12T11:39:09.8966667+00:00

I am facing some difficulty when I am trying to find out the count of repeated words in C#.

Code:

using System;
using System.Collections.Generic;
                
public class Program
{
    public static void Main()
    {
        //string[] _list = []; ;
        List<string> a = new List<string>();
        //bool inWord = false;
        string[] arr = {"hello","test","hello","raf"};
            int _counter = 0;
        //int c = 0;
        
        for (int i = 0; i<arr.Length; i++)
        {     
             if (a.Contains(arr[i]))
            {               
                                //Console.WriteLine("second");
                                 _counter++;
                                Console.WriteLine(arr[i] + " : " + _counter); 
            }
            else
            {
                 a.Add(arr[i]); 
                //Console.WriteLine("first");
                _counter++;
                Console.WriteLine(arr[i] + " : " + _counter); 
                //inWord = true;
                //inWord = false;
            }
            _counter = 0;
                 }  
    }
}


Current output looks like:

hello : 1
test : 1
hello : 1
raf : 1

But I want:

hello : 2
test : 1
raf : 1


need help

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2025-04-12T11:46:41.5633333+00:00

    If you are interested in LINQ:

    string[] arr = ["hello", "test", "hello", "raf"];
    
    foreach( var g in arr.GroupBy( a => a ) )
    {
        Console.WriteLine( $"{g.Key}: {g.Count( )}" );
    }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Thomas Wycichowski TWyTec 1,040 Reputation points
    2025-04-12T13:19:02.74+00:00

    This is also a way

    //string[] _list = []; ;
    Dictionary<string, int> a = new Dictionary<string, int>();
    //bool inWord = false;
    string[] arr = { "hello", "test", "hello", "raf" };
    //int c = 0;
    for (int i = 0; i < arr.Length; i++)
    {
        string key = arr[i];
        if (a.TryGetValue(key, out int value))
        {
            a[key] = ++value;
            Console.WriteLine($"{key} : {value}");
        }
        else
        {
            a.Add(key, 1);
            Console.WriteLine($"{key} : 1");
        }
    }
    Console.WriteLine($"--------------------------------");
    foreach (var item in a)
    {
        Console.WriteLine($"{item.Key} : {item.Value}");
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.