Read column headers in CSV using fileHelpers library

时光毁灭记忆、已成空白 提交于 2019-12-24 02:04:02

问题


I have a CSV file where the headers indicate in which order the information is going to appear in the detail lines. An example would be:

COLUMN1,COLUMN2,COLUMN3
VALUE1,VALUE2,VALUE3

but could also be

COLUMN2,COLUMN3,COLUMN1
VALUE2,VALUE3,VALUE1

The class would look like this

public class CSVImportLineItem
{
    public string Column1 {get; set;}
    public string Column2 {get; set;}
    public string Column3 {get; set;}
}

Is there a way (using FileHelpers) to read the headers in and then determine the mapping to the properties based on the header order?


回答1:


Any reason why you have to specifically use the FileHelpers library?

  //Use File.ReadAllLines();
  List<string> lines = new List<string>() { "Column1, Column2, Column3", "1,2,3" };
  var cols = lines.First().Split(',');
  List<CSVImportLineItem> imported = new List<CSVImportLineItem>();
  var v = lines.Skip(1).ToList().Select(line =>
     {
       CSVImportLineItem item = new CSVImportLineItem();
       var values = line.Split(',');
       for (int i = 0; i < cols.Count(); i++)
       {
         item.GetType().GetProperty(cols[i].Trim()).SetValue(item, values[i], null);
       }
       return item;
     }).ToList();



回答2:


You can use the one of the ClassBuilder helper classes.

DelimitedClassBuilder cb = new DelimitedClassBuilder("LineItem");
// First field
cb.AddField("Column2", typeof(string));
// Second field
cb.AddField("Column1", typeof(string));
// Third field
cb.AddField("Column3", typeof(string));

engine = new FileHelperEngine(cb.CreateRecordClass());
LineItem[] lineItems = engine.ReadFile("FileIn.txt") as LineItem[];

You can change the order of the fields based on the contents of the first line (which you can read outside of FileHelpers).

See also, the answer here.



来源:https://stackoverflow.com/questions/14704642/read-column-headers-in-csv-using-filehelpers-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!