2

我正在尝试使用以下 C# 代码输出到文本文件。问题是我输出的信息末尾有一个逗号,这不适用于之后使用该文件的程序。我试图弄清楚如何摆脱这个逗号......

var toFile = Path.Combine(GetTextPath(),
    string.Format(heatname + "_{0}.txt", DateTime.Now.ToString("yyyyMMdd")));
            string ElementsNum = RoundedValues.Count.ToString();
            DateTime dt = System.DateTime.Now;
            var year = dt.ToString("yy");
            var month = dt.ToString("MM");
            var day = dt.ToString("dd");
            var minute = dt.ToString("mm");
            using (var fs = File.OpenWrite(toFile))
            using (TextWriter sw = new StreamWriter(fs))
            {
                sw.Write("NA" + "," + dt.Hour.ToString() + "," + minute + "," + day + ","
                                      + month + "," + year + "," + "ALTEST " + "," +
                                      "ALTEST " + "," + heatgrade + "    " + "," + "    " + "," + heatname + "," +
                                      DT2.Rows[0][3].ToString() + "," + heatgrade + "," + "OE2" + "," + "," +
                                      "," + "," + "," + "," + "," + " " + ElementsNum);

                foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
                {
                    sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
                }
            }
4

3 回答 3

2

您可以使用TrimEnd,例如:

var theString = "abcd,";
var trimmedString = theString.TrimEnd(new[]{','});

就您而言,如果我没记错的话,这就是您希望它发生的地方:

sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");

如果是这样,您可以这样做:

var pairs = pair.B.ToString() + ", " + pair.A.ToString() + ",";
sw.Write(pairs.Trim().TrimEnd(new[]{','}));
于 2013-04-25T01:07:09.783 回答
1

这是一种 linqy 方法。这将使用 linq 的聚合函数。

var x = RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b })    
  .Aggregate("", (old, item) => {
            return old + (old == "" ? "" : ", ") + 
               item.B.ToSTring() + ", " + item.A.ToString();
   });
sw.Write(x);

版本二(go go join!)使用 linq 创建一个包含对的字符串数组,然后使用 join 将这些对以逗号分隔。

string [] x = RoundedValues.Zip(Elements, 
     (a, b) => b.ToSTring() + ", " + a.ToString() ).ToArray();
sw.Write(String.Join(", ",x));

可能以下方法可行,但我无法测试它......这看起来确实很性感(主要是因为它是一条线,每个人都喜欢一条线解决方案):

sw.Write(String.Join(", ",
   RoundedValues.Zip(Elements, 
     (a, b) => b.ToSTring() + ", " + a.ToString() )
));

哪个会取代

foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
   sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
}
于 2013-04-25T01:09:46.773 回答
0

另一种选择是使用 StringBuilder。

...
StringBuilder sb = new StringBuilder();

foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
    sb.AppendFormat("{0}, {1},", pair.B, pair.A);
}
sw.Write(sb.ToString().TrimEnd(new[] { ' ', ',' });
于 2013-04-25T01:44:27.273 回答