用于创建批量文件的算法

时间:2014-02-16 17:51:48

标签: c# algorithm lambda expression linq-query-syntax

我有一个目录,其中所有具有不同版本的文件都可用。 像,

ABC.pdf ABC_1.pdf .......

XYZ.tif ..... XYZ_25.tif

MNO.tiff

我想根据使用的要求制作n批m文件。

假设,在文件夹中我有ABC.pdf到ABC_24.pdf& XYZ.tif到XYZ_24.tif文件。共50个文件。我想创建两批25个文件。因此,首先(我/如何)需要确保列表中的所有文件都已排序,然后我可以执行一些逻辑将列表分成两个正确的批次。

1)ABC.pdf到ABC_24.pdf

2)XYZ.tif到XYZ_24.tif

但如果我有26个文件(如开头所述)那么就像

1)ABC.pdf到ABC_24.pdf

2)XYZ.tif到XYZ_24.tif

3)ABC_25.pdf和XYZ_25.tif

所以,我想要在这里进行适当/有意义的批量文件分配。 我宁愿尽可能少地执行任务。 所以,我尝试了lambda表达式如下:

List<string> strIPFiles =  Directory.GetFiles(folderPath, "*.*").
Where(file => file.ToLower().EndsWith("tiff") || file.ToLower().EndsWith("tif") || file.ToLower().EndsWith("pdf")).ToList();

int batches = 2, filesPerBatch = 25; //for example

我需要使用 - strIPFiles.Sort();无论如何它会有用吗?或者我总是会得到文件的排序列表?

如何使用lambda表达式从列表中创建批次?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

不确定我是否完全理解你的问题。我假设您正在寻找一种方法将文件分成指定大小的批次(如文件#中),并且您还希望它们根据文件名进行分组。

请告诉我这是否有用:

    public static void CreateBatch(int batchSize)
    {
        string sourcePath = @"C:\Users\hari\Desktop\test";

        var pdfs = Directory.EnumerateFiles(sourcePath, "*.pdf", SearchOption.TopDirectoryOnly);
        var tiffs = Directory.EnumerateFiles(sourcePath, "*.tiff", SearchOption.TopDirectoryOnly);

        var images = pdfs.Union(tiffs);

        var imageGroups = from image in images
                          group image by Regex.Replace(Path.GetFileNameWithoutExtension(image), @"_\d+$", "") into g
                          select new { GroupName = g.Key, Files = g.OrderBy(s => s) };

        List<List<string>> batches = new List<List<string>>();
        List<string> batch = new List<string>();

        foreach (var group in imageGroups)
        {
            batch = batch.Union(group.Files).ToList<string>();

            if (batch.Count >= batchSize)
            {
                batches.Add(batch);
                batch = new List<string>();
            }
        }            
    }