Home > Enterprise >  Write a program that outputs folders with the same names
Write a program that outputs folders with the same names

Time:04-16

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);

CodePudding user response:

        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();
  •  Tags:  
  • c#
  • Related