0

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

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 表达式?

谢谢你的帮助。

4

1 回答 1

3

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

让我知道这是否有帮助:

    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>();
            }
        }            
    }
于 2014-02-17T07:36:08.607 回答