どうやら、Fastmember は匿名オブジェクトのプロパティを列挙することができません。したがって、作成されたデータ リーダーには列がなく、DataTable.Load メソッドはこのリーダーの空の行の作成を拒否します。
可能であれば、具象クラスで試してください。
class Thingy
{
public int Number { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Thingy> list = new List<Thingy>() { new Thingy { Number = 500 } };
DataTable table = new DataTable();
using (var reader = ObjectReader.Create(list))
{
table.Load(reader);
}
}
}
編集:実際には、Fastmember はこれらのプロパティに完全にアクセスできますが、ジェネリック リスト (オブジェクト) の型により、それらを参照できません。IEnumerable に実際のランタイム タイプを指定できる場合にも機能するはずです。
//This creates a "strongly" typed list, instead of List<object>:
var list = new[] { (new { Number = 500 }) }.ToList();
DataTable table = new DataTable();
using (var reader = ObjectReader.Create(list))
{
table.Load(reader);
}
編集 2:コンストラクターを使用して型情報を Fastmember に渡すさらに別の方法があります。
List<object> list = new List<object> { new { Number = 500 } };
DataTable table = new DataTable();
// Note that type information is derived directly from the first object in the list,
// so try not to pass an empty one :)
using (var reader = new ObjectReader(list[0].GetType(), list, null))
{
table.Load(reader);
}
また、アイテムの種類が混在するリストを作成できるため、これは他の方法よりもリスクが高いことに注意してください。Fastmember では、リスト内のすべての項目がまったく同じ型である必要があり、次のような場合に例外が発生します。
//These two items are not of the same type. Look carefully at the "Extra" property:
List<object> list = new List<object> { new { Number = 500, Extra = true }, new { Number = 500, Extra = "Boom" } };