如何在循环内修剪

时间:2013-04-25 00:59:37

标签: c# asp.net-mvc-4

我正在尝试使用以下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() + ",");
                }
            }

3 个答案:

答案 0 :(得分: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[]{','}));

答案 1 :(得分:1)

这是一种很有效的方法。这将使用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() + ",");
}

答案 2 :(得分: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[] { ' ', ',' });