c#将列添加到CSV文件的末尾

CM9*_*M99 4 c# csv

试图在cvs文件的末尾添加一个列,这将只计算行数(或者可以是所有相同的数字,它实际上并不重要),因为主要目的是添加一个包含一些数据的新列在里面.

我有的示例CSV文件有3列,每列都有一些随机数据.

我现在拥有的是

    List<string> newColumnData = new List<string>() { "D" };
    List<string> lines = File.ReadAllLines(@"C:/CSV/test.csv").ToList();

    //add new column to the header row
    lines[0] += ",Column 4";
    int index = 1;

    //add new column value for each row.
    lines.Skip(1).ToList().ForEach(line =>
    {
        //-1 for header
        lines[index] += "," + newColumnData[index - 1];
        index++;
    });
    //write the new content
    File.WriteAllLines(@"C:/CSV/test.csv", lines);
Run Code Online (Sandbox Code Playgroud)

然而,这会引发异常"索引超出范围必须是非负且小于集合的大小"

任何建议都会一如既往地受到欢迎.

小智 7

你不应该在foreach中编入索引.foreach一次为您提供一条线.

lines.Skip(1).ToList().ForEach(line =>
{
    //-1 for header
    line += "," + newColumnData[index - 1];
    index++;
});
Run Code Online (Sandbox Code Playgroud)

lambda表达式意味着:获取列表中的每个元素,并将其称为"line",并对其进行大括号内的操作.

另外,正如我在这里看到的那样,你的newColumnData似乎只有一个项目,字符串"D".然而,您正在为它编制索引,就好像此列表中有一个项目是您阅读的csv文件中的每一行.如果你的csv文件中有多行,那么这也会导致索引超出范围,但是......没关系,我想的越多,你应该跟Dmitry Bychenko的答案越多.


Dmi*_*nko 5

为什么这么多实现 ReadAllLines(),.ToList()?为什么不呢

String filePath = @"C:/CSV/test.csv";

var csv = File.ReadLines(filePath) // not AllLines
  .Select((line, index) => index == 0 
     ? line + ",Column 4"
     : line + "," + index.ToString())
  .ToList(); // we should write into the same file, that´s why we materialize

File.WriteAllLines(filePath, csv);
Run Code Online (Sandbox Code Playgroud)