Fun Coding

学んだことを記録していきます!

【C#】データテーブルをリストに変換する方法

データテーブルをリストに変換する方法を
サンプルコードを交えて解説したいと思います。

説明

・要素の追加
① 行を取得
② GetPropertiesメソッドでプロパティを取得
③ プロパティと同じ名前の列の行の値を取得
④ プロパティに行の値を設定
⑤ 要素を追加


リストをデータテーブルに変換したい場合は以下を参考にしてください。
funcording.hatenablog.com

コード
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace Sample {
    /// <summary>
    /// メインプログラム
    /// </summary>
    public class Program {
        /// <summary>
        /// データテーブルをリストに変換
        /// </summary>
        static void Main() {
            // テーブルの生成
            var table = new DataTable();

            // テーブルに列を追加
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Age", typeof(int));

            // テーブルに行を追加
            table.Rows.Add("一郎", 10);
            table.Rows.Add("二郎", 20);
            table.Rows.Add("三郎", null);



            // リストの生成
            var personList = new List<Person>();

            // 要素の追加
            foreach(DataRow row in table.Rows) {
                // 要素の作成
                var person = new Person();
                // 値を設定
                foreach(PropertyInfo property in typeof(Person).GetProperties()) {
                    property.SetValue(person, row[property.Name] == DBNull.Value ? null : row[property.Name]);
                }
                // 追加
                personList.Add(person);
            }


            // 要素を出力
            foreach(Person person in personList) {
                Console.WriteLine(nameof(person.Name) + " : " + person.Name + ", " + nameof(person.Age) + " : " + person.Age);
            }
        }
    }

    /// <summary>
    /// 人間テーブルのエンティティクラス
    /// </summary>
    public class Person {
        /// <summary>
        /// 名前を取得/設定
        /// </summary>
        public string? Name {
            get;
            set;
        }

        /// <summary>
        /// 年齢を取得/設定
        /// </summary>
        public int? Age {
            get;
            set;
        }
    }
}
出力
Name : 一郎, Age : 10
Name : 二郎, Age : 20
Name : 三郎, Age :