##CSVに配列のカラムを定義したくなったのでメモ
###使用ライブラリ
- CSVHelper
http://joshclose.github.io/CsvHelper/
##今回使用したサンプル
読み込んだCSVファイル
ID,name,link,param[0],param[1],param[2]
1,example,http://www.example.com,1,2,3
2,example2,http://www.excample2.com,3,4,5
using System;
using CsvHelper;
using CsvHelper.Configuration;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace csv_mapping
{
class MainClass
{
public static void Main(string[] args)
{
var csv = new CsvReader(new StreamReader("test.csv"));
csv.Configuration.RegisterClassMap<TestMap>();
foreach (var t in csv.GetRecords<Test>())
{
Console.WriteLine(t.ToString());
}
}
}
public sealed class TestMap : CsvClassMap<Test>
{
public TestMap()
{
Map(t => t.ID);
Map(t => t.name);
Map(t => t.link);
Map(t => t.param).ConvertUsing(row => {
var result = new List<int>();
result.Add(row.GetField<int>("param[0]"));
result.Add(row.GetField<int>("param[1]"));
result.Add(row.GetField<int>("param[2]"));
return result;
});
}
}
public class Test
{
public int ID { get; set; }
public string name { get; set; }
public string link { get; set; }
public List<int> param { get; set; }
public override string ToString()
{
return string.Format("[Test: ID={0}, name={1}, link={2}, param={3}]", ID, name, link, param.toString());
}
}
public static class Extension
{
public static string toString<T>(this IEnumerable<T> self)
{
return string.Join(",", Array.ConvertAll<T, string>(self.ToArray(), o => o.ToString()));
}
}
}
確認結果
[Test: ID=1, name=example, link=http://www.example.com, param=1,2,3]
[Test: ID=2, name=example2, link=http://www.excample2.com, param=3,4,5]