【问题标题】:How can I format a column from a tab separated file?如何格式化制表符分隔文件中的列?
【发布时间】:2020-12-18 03:07:28
【问题描述】:

C# 和 Linq 的新手。我已经尝试过搜索,但我似乎无法到达任何地方。

我正在尝试格式化文件中的最后一列。这是一个货币值,我想将其格式化为显示 2 位小数。

这个功能是拆分数据和排序文件。我认为将文件重新组合在一起时应该进行格式化,但我不确定如何实现。

static void SortData(string directory, string outputDirectory)
{
    var d = new DirectoryInfo(directory);
    Console.WriteLine("Sorting Files...");

    foreach (FileInfo fi in d.GetFiles())
    {
        // Read file
        var fileContents = File.ReadAllText(directory+ fi.Name);

        //split on carriage returns and line feeds, remove empty entries.
        var lines = fileContents.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

        //Split each line on Tab
        var splitLines = lines.Select(l => l.Split(new[] { '\t' }));

        //splitLines is now an array of arrays.  Each splitLine entry is a line, and each entry of each splitline element is
        //a single field... so we should be able to sort how we want, e.g. by first field then by second field:
        var sortedLines = splitLines.OrderBy(sl => sl[0]).ThenBy(sl => sl[1]).ThenBy(sl => sl[2]).ThenBy(sl => sl[3]).ThenBy(sl => sl[4]).ThenBy(sl => sl[5]).ThenBy(sl => sl[6]);

        //put back together as TSV - put tabs back.
        var linesWithTabsAgain = sortedLines.Select(sl => string.Join("\t", sl));

        //put carriage returns/linefeeds back
        var linesWithCRLF = string.Join("\r\n", linesWithTabsAgain);

        File.WriteAllText(outputDirectory + fi.Name, linesWithCRLF);
    }

    Console.WriteLine("Sorting Complete");
}

【问题讨论】:

  • 如果要将所有数字格式化为“2个小数位”,最好先decimal.Parse(value)在排序前得到一个小数[][],然后用.ToString("F2")格式化在文件写入之前。

标签: c# linq file csv


【解决方案1】:

因此,您需要做的是,在拆分数据后,对于每一行或每一行,将字符串值解析为数字,然后将其格式化回字符串,但包含 2 位数字。 在var sortedLines = splitLines..... 之后添加以下行:

foreach(var sl in sortedLines)
{
    sl[6]=decimal.Parse(sl[6]).ToString("F2");
}

【讨论】:

    猜你喜欢
    • 2017-09-07
    • 2012-03-07
    • 2023-04-07
    • 2010-11-24
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2014-03-10
    • 2013-01-21
    相关资源
    最近更新 更多