读取csv文件并将数据存储在2-D对象数组中 [英] Reading a csv file and storing the data in a 2-D object array

查看:307
本文介绍了读取csv文件并将数据存储在2-D对象数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,如果csv文件(例如日期和价格)包含一些空单元格,那么当我尝试将数据存储在列表中时如何解决此问题?

First, if the csv file (eg: Date and Price) contains some empty cells, how can I solve this problem when I try to store the data in a list?

第二,两个列表都可以后,我想知道如何创建一个二维对象,例如PriceByDate[100,2](Date[100,0],Price[100,1]),该对象可以存储csv文件中的数据.

Second, once the two lists are okay I'd like to know how to create a 2-D object such as PriceByDate[100,2](Date[100,0],Price[100,1]) which can store the data from the csv file.

预先感谢

这是我的代码:(不起作用)

Here is my code:(Not work)

var reader = new StreamReader(File.OpenRead(@"filenames"));

List<string> Dates = new List<string>();
List<string> Prices = new List<double>();
while (!reader.EndOfStream)
{
    var line = reader.ReadLine();
    var values = line.Split(';');

    listA.Add(values[0]);
    listB.Add(values[1]);
} 

DateTime[] s = Convert.ToDateTime(ListA.toArray());
double[] o = ListB.toArray();
object[,] PriceByDate = new object[,]{{s},{o}};

推荐答案

本文介绍了如何使用ADO.net读取CSV文件.这很简单.使用此方法,您的日期和价格信息将位于已经配对的行/记录对象上.

This article show how to use ADO.net to read a CSV file. It is pretty simple. Using this method your Date and Price information will be on a row/record object already paired.

文章:在ADO.NET中读取CSV文件

如果使用上述文章解决方案,则只需做一个简单的字符串即可.对记录的字段进行IsNullOrEmpty测试.如果函数返回true,则可以跳过行/记录.

If you use the above articles solution, all you need to do is a simple string.IsNullOrEmpty test on the fields of the record. If the function returns true you can skip the row/record.

我不确定这是否是您在"2-D"对象中正在寻找的东西.如果您需要在代码中创建一个对象以从记录中读取数据后保存数据,则可以使用类似的方法.附带一提,您可能还想使用小数点表示货币值.

I'm not sure if this is what you are looking for as in a "2-D" object. If you need to create an object in your code to hold the data after reading it from the record I would use something like this. On a side note you may also want to use a decimal for holding monetary values.

public class PriceAndDate
{
    public DateTime Date {get;set;}
    public Decimal Price {get;set;}
}

List<PriceAndDate> priceAndDate = new List<PriceAndDate>();

这篇关于读取csv文件并将数据存储在2-D对象数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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