如何切换CSV文件的列(C#)

时间:2018-06-22 03:45:22

标签: c#

我有一个5列CSV文件,我需要将第三列放在最前面。

我该怎么做? 以下是我认为我必须做的。

     //Basically I have to make a fore loop which results in a multidimensional array
        //Then write another for loop switching the colums of the array around
        //Then sorting it
        //then saving it

更新:csv文件如下

string,string,double,double,string

例如

John,Smith,.464,10.5,单词和其他内容

还应该提到,此过程必须是可逆的,这意味着需要将移动的列放回原处。

2 个答案:

答案 0 :(得分:0)

一个简单的读写循环就可以完成工作,而无需将所有数据加载到内存中。

注意:以下解决方案假定一个简单的CSV文件,其中的字段不包含定界符(“,”),并且每一行包含相同数量的列。

    /// <summary>
    /// Move a csv file column to a new position. File is modified in place.
    /// </summary>
    public void MoveCsvColumn(string file, int column, int position, string delimeter = ",")
    {
        using (var reader = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Write)))
        using (var writer = new StreamWriter(new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.Read)))
        {
            while (!reader.EndOfStream)
            {
                // Read the line
                var line = reader.ReadLine().Split(new string[] { delimeter }, StringSplitOptions.None);

                // Move the column within the array of columns
                MoveColumn(line, column, position);

                // write the output
                writer.WriteLine(string.Join(delimeter, line));
            }
        }
    }

    /// <summary>
    /// Move a column within the array to the new destination
    /// </summary>
    public void MoveColumn(object[] line, int from, int to)
    {
        to = Math.Max(0, Math.Min(line.Length - 1, to));

        if (from == to 
            || from < 0 
            || from >= line.Length)
        {
            return;
        }

        while (from != to)
        {
            if (from > to)
            {
                // percolate down
                Swap(line, from, from-1);
                from--;
            }
            else
            {
                // percolate up
                Swap(line, from, from + 1);
                from++;
            }
        }
    }

    /// <summary>
    /// Swap values positions within the array
    /// </summary>
    public void Swap(object[] line, int a, int b)
    {
        var tmp = line[a];
        line[a] = line[b];
        line[b] = tmp;
    }

答案 1 :(得分:-2)

最初,我在评论中发布了我的解决方案,但我认为它应该得到正确的答案。

  

我有一个5列CSV文件,我需要将第三列放在最前面。我该怎么做呢?

  1. 使用您喜欢的电子表格程序打开文件
  2. 将第三列拖到左侧
  3. (根据需要创建排序)
  4. 保存
  5. 工作完成

现在,有些读者可能会争辩说,该问题被标记为C#,因此我的答案将无效。我在争辩说OP从来没有提供任何证据表明必须通过编程语言来解决这样的任务(请考虑XYProblem),从而使可接受的答案像OP的问题一样含糊不清(电子表格程序很容易获得这样的答案)

@Gooyan随时更新您的问题,并提供更多详细信息,说明您需要达到什么目的(以及为什么),已经尝试了什么(如果有的话),我将很乐意相应地更新我的答案。