【问题标题】:dynamic string formatting using string.format and List<T>.Count()使用 string.format 和 List<T>.Count() 进行动态字符串格式化
【发布时间】:2009-06-07 23:03:20
【问题描述】:

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

例如

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

Part_0001_Filename.pdf...Part_1000_Filename.pdf

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

Part_001_Filename.pdf...Part_500_Filename.PDF

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

【问题讨论】:

  • 事实上,Explorer 实际上使用自然数字排序,即使没有前导零,它也会以正确的顺序对数字进行排序。
  • @Johannes:也许这在 Vista/7 中是正确的,但我很确定它在 XP 中不会这样工作。我可能是错的,但我记得当我列举文件时,它们的顺序与 Explorer 显示的顺序不同。

标签: c# string formatting


【解决方案1】:

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

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

【讨论】:

  • @Jon:非常感谢您的帮助。我使用您的 LINQ 实现将每个文件的格式字符串存储在我创建的列表中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
相关资源
最近更新 更多