将CSV文件读取到两个数组c# [英] Read CSV files to two arrays c#

查看:170
本文介绍了将CSV文件读取到两个数组c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个情况,需要从csv文件的每一列创建两个数组。如下所示,csv文件包含两列,每列都有一个标题为'period'和'acceleration'的标题。

I have a situation that need to make two arrays from each column of csv file. As shown below, the csv file contain two columns each column has a header titled 'period' and 'acceleration'.

Period,Acceleration
0.01,0.6
0.05,0.82
0.1,1.26
0.15,1.403
0.2,1.383

我尝试使用以下代码,然后拆分这成两个数组。但是,它没有以逗号分隔数字。

I tried to use following code and then split this into two arrays. However, it did not break the numbers by comma.

string[] allLines = File.ReadAllText(@"C:\ArsScale\Tars.csv").Split(',');


推荐答案

static void getTwoArraysFromFile(string filein, ref double[] acc, ref double[] period)
{
    string line;

    List<double> p1 = new List<double>();
    List<double> p2 = new List<double>();

    System.IO.StreamReader file = new System.IO.StreamReader(filein);
    while ((line = file.ReadLine()) != null)
        try {
            String[] parms = line.Trim().Split(',');

            p1.Add(double.Parse(parms[1], CultureInfo.InvariantCulture));       
            p2.Add(double.Parse(parms[0], CultureInfo.InvariantCulture));
        }
        catch { }

    acc = p1.ToArray();
    period = p2.ToArray();
}

这篇关于将CSV文件读取到两个数组c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆