For your first example in particular would suffice:
dataTable1.AsEnumerable().Select(dr => new { ID = dr["ID"], Name = dr["Name"] });
But for a more generic solution the (little known) Expandoobject:
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"
}
}
}
Is there a project that was used as an example to facilitate?
– user33805
Take a look in that library ;)
– talles