Skip to content

Instantly share code, notes, and snippets.

@KentaYamada
Created December 2, 2014 04:55
Show Gist options
  • Save KentaYamada/3608ee900aa0baff980c to your computer and use it in GitHub Desktop.
Save KentaYamada/3608ee900aa0baff980c to your computer and use it in GitHub Desktop.
List<T>からDataTable型へ変換する
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ListToDataTable
{
class Program
{
static void Main(string[] args)
{
var l = new List<Sample>();
l.Add(new Sample(1, "yaamda"));
l.Add(new Sample(2, "kameya"));
var table = CvtTable(l);
foreach (DataRow r in table.Rows)
{
foreach(DataColumn c in table.Columns)
{
Console.Write("{0},", r[c]);
}
}
Console.ReadKey();
}
private static DataTable CvtTable(List<Sample> samples)
{
var table = new DataTable();
var target = samples.GetType().GetGenericArguments()[0];
foreach (var p in target.GetProperties())
{
table.Columns.Add(p.Name, p.PropertyType);
}
foreach (Sample l in samples)
{
var row = table.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
{
var prop = l.GetType().GetProperties()[i];
row[i] = prop.GetValue(l, null);
}
table.Rows.Add(row);
}
return table;
}
}
public class Sample
{
public Sample(int id, string name)
{
this.ID =id;
this.Name = name;
}
public int ID { get; set; }
public string Name { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment