CSV to object model mapping

后端 未结 6 661
礼貌的吻别
礼貌的吻别 2020-12-01 07:51

I have a CSV file that I want to read into a List. Here\'s an example file:

Plant,Material,\"Density, Lb/ft3\",Storage Location
FRED,10000477,64.3008,3300
F         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 08:20

    I wrote a simple library to allow developers to use LINQ on CSV files. Here is my blog post about it: http://procbits.com/2010/10/11/using-linq-with-csv-files/

    In your case, you would have to change your header string to look like this:

    Plant,Material,DensityLbft3,StorageLocation
    

    And then you could parse the file like this:

    var linqCSV = new CsvToXml("csvfile", true);
    linqCsv.TextQualifier = null;
    
    linqCsv.ColumnTypes.Add("Plant", typeof(string));
    linqCsv.ColumnTypes.Add("Material", typeof(int));
    linqCsv.ColumnTypes.Add("DensityLbft3", typeof(double));
    linqCsv.ColumnTypes.Add("StorageLocation", typeof(int));
    
    linqCsv.Convert();
    

    You could then use LINQ like this:

    var items = from item in linqCsv.DynamicRecords
                where item.Plant == "Fred" && item.DensityLbft3 >= 62.6
                orderby item.StorageLocation
                select item;
    

    Hope that helps or works for you.

提交回复
热议问题