Help us understand the problem. What is going on with this article?

CSV をクラスにバインドする (C#)

CSV をクラスにバインドする (C#)

例えば

RowId,Id,StartDate,StopDate,CustomerId
0,C0001,2020-03-01T00:00:00.0000000,2020-04-01T00:00:00.0000000,0
1,C0002,2020-03-01T00:00:00.0000000,,1

みたいな CSV があって

public class Contract
{
    public int RowId { get; set; }
    public string Id { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime? StopDate { get; set; }
    public int CustomerId { get; set; }
}

にバインドしたいという話です. CSV パーサは今回は話題にしたくないので、string.Split(",") で片付くということにしましょう.

以下みたいなコードを書くと、var contracts = Load<Contract>(fstream).ToArray(); でバインドできます.

public static T Bind<T>(Dictionary<string, int> headerMap, string[] values)
    where T : class, new()
{
    var result = new T();
    foreach (var p in typeof(T).GetProperties())
    {
        if (!headerMap.ContainsKey(p.Name)) continue;
        var value = values[headerMap[p.Name]];

        var type = Nullable.GetUnderlyingType(p.PropertyType);
        if (type == null)
        {
            type = p.PropertyType;
        }
        else
        {
            if (value == "")
            {
                p.SetValue(result, null);
                continue;
            }
        }

        if (type == typeof(int))
        {
            p.SetValue(result, int.Parse(value));
        }
        else if (type == typeof(bool))
        {
            p.SetValue(result, bool.Parse(value));
        }
        else if (type == typeof(string))
        {
            p.SetValue(result, value);
        }
        else if (type == typeof(DateTime))
        {
            if (!DateTime.TryParseExact(value, "o", null, DateTimeStyles.RoundtripKind, out var _))
            {
                value = DateTime.Parse(value).ToString("o");
            }
            p.SetValue(result, DateTime.ParseExact(value, "o", null, DateTimeStyles.RoundtripKind));
        }
        else
        {
            throw new ApplicationException($"Unsupported type: {typeof(T).Name}");
        }
    }
    return result;
}

public static IEnumerable<T> Load<T>(Stream stream, Encoding encoding = null)
    where T : class, new()
{
    if (encoding == null) encoding = Encoding.UTF8;
    using (var reader = new StreamReader(stream, encoding))
    {
        var header = reader.ReadLine().Split(",");
        var headerMap = new Dictionary<string, int>();
        for (var i = 0; i < header.Length; i++)
        {
            headerMap[header[i]] = i;
        }

        while (true)
        {
            var line = reader.ReadLine();
            if (line == null) break;
            yield return Bind<T>(headerMap, line.Split(","));
        }
    }
}

なお、プロパティではなくフィールドにしたい場合には .GetProperties().GetFields() になり、.PropertyType.FieldType になります.

aまた、class ではなく struct にしたい場合には、where T : class, new()where T : struct になり、var result = new T();var result = default(T); になり、p.SetValue(result, v);p.SetValueDirect(__makeref(result), v); になります.

関連記事: クラスを CSV にデバインドする (C#)

c-yan
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした