将逗号分隔的数据集拆分为单独的数组

时间:2012-10-03 03:33:05

标签: c#

我有一个我想修改的.csv文件。这是文件的格式:

  Id, UTMGridEast, UTMGridNorth, LocDate, LocTime, Species

我已经完成的是创建所有这些值的arraylist,但我想要做的是创建所有值的arraylist,数据集中的每一行都是另一个数组。这是因为我需要编辑字段UTMGridEastUTMGridNorth,然后将它们重新插入到arraylist中。

我的GUI只包含两个按钮,这是我目前的代码:

public partial class MainWindow : Window
{
    private string _filename;

    private string[] _splitValues;

    public MainWindow()
    {
        InitializeComponent();
    }

private void btnLoad_Click(object sender, RoutedEventArgs e)
    {
        // Configure open file dialog box
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.FileName = "Dataset"; // Default file name
        dlg.DefaultExt = ".txt"; // Default file extension
        dlg.Filter = "Commar Seperated Values (.csv)|*.csv" ; // Filter files by extension 

        // Show open file dialog box
        Nullable<bool> result = dlg.ShowDialog();

        // Process open file dialog box results 
        if (result == true)
        {
            // Open document 
            _filename = dlg.FileName;
            txtFilePath.Text = _filename;
        }
    }

    private void btnConvert_Click(object sender, RoutedEventArgs e)
    {
        ConvertToLatLong();
    }

    private void ConvertToLatLong()
    {
        string textFile = System.IO.File.ReadAllText(_filename);

        foreach (var value in textFile)
        {
            _splitValues = textFile.Split(',');
            Console.WriteLine("Split values: " + _splitValues[value]); 
        }

    }
}

2 个答案:

答案 0 :(得分:1)

首先,我会根据NewLine分割文本,以获取单独的行,然后根据字段分隔符。

类似

List<string> lines = new List<string>(textFile.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
for (int iLine = 0; iLine < lines.Count; iLine++)
{
    List<string> values = new List<string>(lines[iLine].Split(new[] {","}, StringSplitOptions.None));
        for (int iValue = 0; iValue < values.Count; iValue++)
            Console.WriteLine(String.Format("Line {0} Value {1} : {2}", iLine, iValue, values[iValue]));
}

但正如我一直所说,滚动你自己的CSV解析器非常困难。

查看Comma-separated values

特别是在基本规则和示例

部分

我要求的是C# Tutorial - Using The Built In OLEDB CSV Parser

答案 1 :(得分:1)

我不确定_splitValues是什么类型,但假设List<String[]>可行:

private void ConvertToLatLong()
{
    var lines = from line in System.IO.File.ReadLines("foo")
                let splitLine = line.Split(',')
                select splitLine.Select(x => x.Trim()).ToArray();
    _splitValues = lines.ToList();
}