猿问

从csv读取到对象[] C#

我正在尝试从 .csv 文件读取到对象数组。


这里还有其他解决方案可以为列表提供解决方案,但我似乎无法让它对我有用。


对象定义:


public class DTOClass

{

    //declare data members

    [DataMember]

    public DateTime Date { get; set; }

    [DataMember]

    public string stock_symbol { get; set; }

    [DataMember]

    public double stock_price_open { get; set; }

    [DataMember]

    public double stock_price_close { get; set; }

    [DataMember]

    public double stock_price_low { get; set; }

    [DataMember]

    public double stock_price_high { get; set; }

    [DataMember]

    public double stock_price_adj_close { get; set; }

    [DataMember]

    public long stock_volume { get; set; }

    [DataMember]

    public string stock_exchange { get; set; }

}

实例声明:


private DTOClass[] _dTOs;

过滤方式:


private List<DTOClass> FromCsv(string csvLine, List<DTOClass> rest)

{

    DataTable _dt = new DataTable();


    string[] values = csvLine.Split(',');


    int j = _dt.Rows.Count;

    for (int i = 0; i < j; i++)

    {

        DTOClass dto = new DTOClass();


        dto.Date = Convert.ToDateTime(values[0]);

        dto.stock_symbol = Convert.ToString(values[1]);

        dto.stock_price_open = Convert.ToDouble(values[2]);

        dto.stock_price_close = Convert.ToDouble(values[3]);

        dto.stock_price_low = Convert.ToDouble(values[4]);

        dto.stock_price_high = Convert.ToDouble(values[5]);

        dto.stock_price_adj_close = Convert.ToDouble(values[6]);

        dto.stock_volume = Convert.ToInt64(values[7]);

        dto.stock_exchange = Convert.ToString(values[8]);


        rest.Add(dto);

    }


    return rest;

}

调用过滤器:


DTO = File.OpenText(Filename).ReadLine().Select(v => FromCsv(v.ToString(), 

_restDto)).ToArray();

我需要它返回到一个对象数组,因为它然后进入数据网格上的 CollectionView。


但我不断收到此错误:


“无法将类型 'System.Collections.Generic.List[]' 隐式转换为 'MBM.Services.DTOClass[]'”


我知道我显然是在返回一个列表列表,但是我已经尝试了其他提供的方法,我只是被难住了。


凤凰求蛊
浏览 342回答 2
2回答

DIEA

一种简单的方法是拆分线条并将它们选择到您的新对象中。var result = File.ReadAllLines("pathTo.csv")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(line => line.Split(','))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(x => new MyObject {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prop1 = x[0],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prop2 = x[1],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //etc..&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToArray();

动漫人物

重新创建轮子没有意义,我只是使用CsvHelper,它支持您正在做的事情,除了处理格式错误的 CSV 之外,您还可以像这样设置映射:public sealed class MyClassMap : ClassMap<MyClass>{&nbsp; &nbsp; public MyClassMap()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; AutoMap();&nbsp; &nbsp; &nbsp; &nbsp; Map( m => m.CreatedDate ).Ignore();&nbsp; &nbsp; }}然后你可以像这样获得对象:var csv = new CsvReader( textReader );var records = csv.GetRecords<MyClass>();
随时随地看视频慕课网APP
我要回答