CSharp · Console
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
public class Program
{
public static void Main()
{
Test t = new Test()
{Property1 = "p1", Property2 = "p2"};
DataTable dt = ObjectToData(t);
var testRow = dt.Rows[0];
Console.WriteLine(testRow["Property1"]);
}
public class Test
{
public string Property1
{
get;
set;
}
public string Property2
{
get;
set;
}
}
public static DataTable ObjectToData(object o)
{
DataTable dt = new DataTable("OutputData");
DataRow dr = dt.NewRow();
o.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
f.GetValue(o, null);
dt.Columns.Add(f.Name, typeof(string));
dr[f.Name] = f.GetValue(o, null);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
);
dt.Rows.Add(dr);
return dt;
}
}