使用string.format和List <t> .Count()</t>进行动态字符串格式化

时间:2009-06-07 23:03:21

标签: c# string formatting

我必须为工作中的项目打印一些PDF。是否有提供动态填充的方法,IE。不使用格式字符串中的硬编码代码。但取而代之的是基于List的计数。

实施例

如果我的列表长度为1000个元素,我想要这个:

Part_0001_Filename.pdf ... Part_1000_Filename.pdf

如果我的列表长500个元素,我想要这个格式:

Part_001_Filename.pdf ... Part_500_Filename.PDF

原因是Windows如何命令文件名。它按字母顺序从左到右或从右到左对它们进行排序,所以我必须使用前导零,否则文件夹中的排序会混乱。

1 个答案:

答案 0 :(得分:9)

最简单的方法可能是动态构建格式字符串:

static List<string> FormatFileNames(List<string> files)
{
    int width = (files.Count+1).ToString("d").Length;

    string formatString = "Part_{0:D" + width + "}_{1}.pdf";

    List<string> result = new List<string>();

    for (int i=0; i < files.Count; i++)
    {
        result.Add(string.Format(formatString, i+1, files[i]));
    }
    return result;
}

如果您愿意,可以使用LINQ稍微简化一下:

static List<string> FormatFileNames(List<string> files)
{
    int width = (files.Count+1).ToString("d").Length;        
    string formatString = "Part_{0:D" + width + "}_{1}.pdf";

    return files.Select((file, index) => 
                            string.Format(formatString, index+1, file))
                .ToList();
}