using System;
using System.Data;
using System.Linq;
namespace ConsoleApplication1
{
public class Emps
{
public string ID { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
// 無理矢理IQueriableに
IQueryable<Emps> q = Enumerable.Range(1, 10).Select(i =>
new Emps { ID = i.ToString(), Name = "田中" + i }).AsQueryable();
// 列情報を組立て
var dt = new DataTable();
var props = q.ElementType.GetProperties();
foreach (var prop in props)
{
dt.Columns.Add(prop.Name, prop.PropertyType);
}
q.AsEnumerable().Select(emp =>
{
var row = dt.NewRow();
foreach (var prop in props)
{
var value = prop.GetValue(emp, null);
if (value != null) row[prop.Name] = value;
}
return row;
}).CopyToDataTable(dt, LoadOption.OverwriteChanges);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(row["ID"] + ", " + row["Name"]);
}
}
}
}