ConvertCsvToList

I create a gist for a helper funtion I used recently to convert a CSV file’s contents to a typed list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private IList<T> ConvertCsvToList<T>(IList<string> csv, string[] header) {
    var list = new List<T>();
    foreach (var row in csv) {
        var columns = row.Split(',');
        T obj = (T)Activator.CreateInstance(typeof(T));
  
        for (int i = 0; i < columns.Length; i++) {
            var h = Regex.Match(header[i].Replace("@", "_"),
                @"(?<="")(?:\\.|[^""\\])*(?="")").Value;
            var c = Regex.Match(columns[i],
                @"(?<="")(?:\\.|[^""\\])*(?="")").Value;
            var prop = typeof(Em.Schools.Data.Domain.Match).GetProperty(h);
            if (prop.PropertyType == typeof(int)) {
                prop.SetValue(obj, Convert.ToInt32(c), null);
            } else {
                prop.SetValue(obj, c, null);
            }
        }
  
        list.Add(obj);
    }
  
    return list;
}