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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/962994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:20:22  来源:igfitidea点击:

dynamic string formatting using string.format and List<T>.Count()

c#stringformatting

提问by Chris

I have to print out some PDFs for a project at work. Is there way to provide dynamic padding, IE. not using a code hard-coded in the format string. But instead based on the count of a List.

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

Ex.

前任。

If my list is 1000 elements long, I want to have this:

如果我的列表有 1000 个元素,我想要这个:

Part_0001_Filename.pdf... Part_1000_Filename.pdf

Part_0001_Filename.pdf... Part_1000_Filename.pdf

And if my list is say 500 elements long, I want to have this formatting:

如果我的列表长度为 500 个元素,我希望采用以下格式:

Part_001_Filename.pdf... Part_500_Filename.PDF

Part_001_Filename.pdf... Part_500_Filename.PDF

The reason for this is how Windows orders file names. It sorts them alphabetically left-to-right or right-to-left, So I must use the leading zero, otherwise the ordering in the folder is messed up.

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

采纳答案by Jon Skeet

The simplest way is probably to build the format string dynamically too:

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

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;
}

This could be done slightly more simply with LINQ if you like:

如果您愿意,可以使用 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();
}