如何将字符串连接到List C#

Ye *_*ung 1 c# asp.net

我试图将字符串添加到List并将列表导出为csv文件,但我得到的结果不是我想要的方式.这是代码 -

List<string> values = new List<string>();
using (StreamReader sr = new StreamReader(filePath))
{
    while (sr.Peek() != -1)
    {
        string line = sr.ReadLine();
        List<string> lineValues = line.Split(',').ToList();
        var tempMinInt = 1;
        var tempValue = 1;
        var tempValInt = Convert.ToInt32(lineValues[4]);
        if (tempValInt % 60 != 0)
        {
            tempMinInt = (tempValInt / 60) + 1;
            tempValue = tempMinInt * 30;
        }
        else
        {
            tempMinInt = tempValInt / 60;
            tempValue = tempMinInt * 30;
        }


        values.Add(lineValues + "," + tempValue.ToString());

    }
}
Run Code Online (Sandbox Code Playgroud)

以下是示例输入数据:

33083,2011-12-19 05:17:57+06:30,98590149,1876,258
33084,2011-12-19 05:22:28+06:30,98590149,1876,69
33085,2011-12-19 05:23:45+06:30,98590149,1876,151
33086,2011-12-19 05:30:21+06:30,98590149,1876,58
33087,2011-12-19 06:44:19+06:30,949826259,1876,66
Run Code Online (Sandbox Code Playgroud)

这是输出数据:

System.Collections.Generic.List`1[System.String],150
System.Collections.Generic.List`1[System.String],60
System.Collections.Generic.List`1[System.String],90
System.Collections.Generic.List`1[System.String],30
System.Collections.Generic.List`1[System.String],60
Run Code Online (Sandbox Code Playgroud)

请指教.谢谢.

Kyl*_*man 5

List<T>不会覆盖ToString,所以你需要在这里做腿部工作.

您可以使用string.Join将列表的值组合成逗号分隔的字符串:

string.Join(",", lineValues.ToArray());
Run Code Online (Sandbox Code Playgroud)

您上面发布的最后一行代码将变为:

values.Add(string.Join(",", lineValues.ToArray()) + "," + tempValue.ToString());
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/57a79xd0.aspx

或者,您可以line在此代码段中使用,因为它lineValues是构建的line,您不会修改任何值.