计算有多少个文件以相同的第一个字符开头c#

Mkz*_*kzz -1 c# io winforms

我想要创建一个函数来计算所选文件夹中有多少个文件以相同的 10 个字符开头。

例如,在文件夹中将有名为 File1、File2、File3 的文件,并且 int count 将给出 1,因为所有 3 个文件都以相同的字符“File”开头,如果在文件夹中将是

File1,File2,File3,Docs1,Docs2,pdfs1,pdfs2,pdfs3,pdfs4 
Run Code Online (Sandbox Code Playgroud)

将给出 3,因为 存在 3 个唯一值fileName.Substring(0, 4)

我已经尝试过类似的方法,但它给出了文件夹中文件的总数。

int count = 0;

foreach (string file in Directory.GetFiles(folderLocation))
{
    string fileName = Path.GetFileName(file);

    if (fileName.Substring(0, 10) == fileName.Substring(0, 10))
    {
        count++;
    }
}
Run Code Online (Sandbox Code Playgroud)

知道如何计算这个吗?

Dmi*_*nko 5

您可以尝试借助Linq查询目录:

using System.IO;
using System.Linq;

...

int n = 10;

int count = Directory
  .EnumerateFiles(folderLocation, "*.*")
  .Select(file => Path.GetFileNameWithoutExtension(file))
  .Select(file => file.Length > n ? file.Substring(0, n) : file)
  .GroupBy(name => name, StringComparer.OrdinalIgnoreCase)
  .OrderByDescending(group => group.Count())
  .FirstOrDefault()
 ?.Count() ?? 0;
Run Code Online (Sandbox Code Playgroud)