For your first example in specific would suffice:
dataTable1.AsEnumerable().Select(dr => new { ID = dr["ID"], Name = dr["Name"] });
But for a more generic solution you can use the (little known) ExpandoObject : / p>
static IEnumerable<dynamic> ObjetoDinamico(this DataTable dt)
{
foreach (DataRow dr in dt.Rows)
{
dynamic dinamico = new ExpandoObject();
foreach (DataColumn dc in dt.Columns)
((IDictionary<string, object>)dinamico)[dc.ColumnName] = dr[dc];
yield return dinamico;
}
}
Example:
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
namespace ConsoleApplication1
{
static class Program
{
static IEnumerable<dynamic> ObjetoDinamico(this DataTable dt)
{
foreach (DataRow dr in dt.Rows)
{
dynamic dinamico = new ExpandoObject();
foreach (DataColumn dc in dt.Columns)
((IDictionary<string, object>)dinamico)[dc.ColumnName] = dr[dc];
yield return dinamico;
}
}
static void Main(string[] args)
{
var dt1 = new DataTable();
dt1.Columns.Add("ID", typeof(int));
dt1.Columns.Add("Name", typeof(string));
dt1.Rows.Add(1, "x");
dt1.Rows.Add(2, "y");
var dt2 = new DataTable();
dt2.Columns.Add("DI", typeof(int));
dt2.Columns.Add("emaN", typeof(string));
dt2.Rows.Add(2, "x");
dt2.Rows.Add(1, "y");
Console.WriteLine(dt1.ObjetoDinamico().First().ID); // 1
Console.WriteLine(dt2.ObjetoDinamico().First().emaN); // "x"
}
}
}