从一组文件名中提取一个模式并放入列表框中

Extract a pattern from a group of filenames and place into listbox

我有一个文件夹,里面有很多这样的文件:

2016-01-02-03-abc.txt
2017-01-02-03-defjh.jpg
2018-05-04-03-hij.txt
2022-05-04-03-klmnop.jpg

我需要从每组文件名中提取模式。 例如,我需要放在列表中的前两个文件中的模式 01-02-03。我还需要将模式 05-04-03 放在同一个列表中。所以,我的列表将如下所示:

01-02-03
05-04-03

这是我目前所拥有的。我可以成功删除字符,但将一个模式的实例重新放入列表超出了我的薪水等级:

        public void GetPatternsToList()
    {
        //Get all filenames with characters removed and place in listbox.

        List<string> files = new List<string>(Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath));
        foreach (var file in files)
        {
            var removeallbeforefirstdash = file.Substring(file.IndexOf("-") + 1); // removes everthing before the dash in the filename
            var finalfile = removeallbeforefirstdash.Substring(0,removeallbeforefirstdash.LastIndexOf("-")); // removes everything after dash in name -- will crash if file without dash is in folder (not sure how to fix this either)

            string[] array = finalfile.ToArray(); // I need to do the above with each file in the list and then place it back in an array to display in a listbox
            List<string> filesList = array.ToList();
            listBox1.DataSource = filesList;
        }

    }

你可以这样做:

public void GetPatternsToList()
{
    var files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);

    var patterns = new HashSet<string>();

    foreach (var file in files)
    {
        var splitFileName = file.Split('-').Skip(1).Take(3);
        var joinedFileName = string.Join("-", splitFileName);

        if(!string.IsNullOrEmpty(joinedFileName)
            patterns.Add(joinedFileName);
    }

    listBox1.DataSource = patterns;
}

我使用了 HashSet<string> 以避免向数据源添加重复模式。

一些与您的问题无关但与您的代码一般相关的评论:

  • 我会将 SelectedPath 作为字符串传递给方法
  • 我会让方法 return 你 HashSet
  • 如果你实现了上面的方法,也请相应地命名方法

以上所有内容当然对您来说都是可选的,但会提高您的代码质量。

试试这个:

public void GetPatternsToList()
{
    List<string> files = new List<string>(Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath));
    List<string> resultFiles = new List<string>();
    foreach (var file in files)
    {
        var removeallbeforefirstdash = file.Substring(file.IndexOf("-") + 1); // removes everthing before the dash in the filename
        var finalfile = removeallbeforefirstdash.Substring(0, removeallbeforefirstdash.LastIndexOf("-")); // removes everything after dash in name -- will crash if file without dash is in folder (not sure how to fix this either)
        resultFiles.Add(finalfile);
    }
    listBox1.DataSource = resultFiles.Distinct().ToList();
}