'Write a program that outputs folders with the same names

I have a program that outputs a list of folders with names. Question, how do I enter the number of folders with the same name in cntPath?

Code:

string firstPath = @"PATH";

        int cnt = 0;
        int cntPath = 0;

        if (Directory.Exists(firstPath))
        {
            string[] dirs = Directory.EnumerateDirectories(firstPath, "*", SearchOption.AllDirectories).ToArray();
            foreach (string dir in dirs)
            {
                DirectoryInfo array = new DirectoryInfo(dir);
                string dirName = array.Name;
                Console.WriteLine("Folder name - {0}.", dirName);
                cnt++;

                //if (dirs[] == d)
                //{
                //    cntPath++;
                //}
            }        
        }
        Console.WriteLine(cnt);
        Console.WriteLine(cntPath);


Solution 1:[1]

        string firstPath = @"PATH";

        int cnt = 0;
        int cntPath = 0;

        if (Directory.Exists(firstPath))
        {
            string[] dirs = Directory.EnumerateDirectories(firstPath, "*", SearchOption.AllDirectories).ToArray();
            var groupedDirs = dirs.Select(r => new DirectoryInfo(r).Name).GroupBy(r => r).ToList();
            foreach (var groupedDir in groupedDirs)
            {
                Console.WriteLine("Folder name - {0} With Count {1}", groupedDir.Key, groupedDir.Count());
            }
        }
        Console.WriteLine(cnt);
        Console.WriteLine(cntPath);
        Console.ReadKey();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dzmitry Tserakhau