How can I convert a DataTable to a dynamic object?

2

How can I convert a DataTable to a IEnumerable<dynamicObject> ?

For example, I want to convert any DataTable

ID | Name          DI | emaN
---------    ou    ---------
 1 | x              2 | x
 2 | y              1 | y

In a list of objects

// list 1      (ex 1)             // list 2    (ex 2)
{                                 {
  { ID = 1, Name = "x" }            { DI = 2, emaN = "x" }
  { ID = 2, Name = "y" }            { DI = 1, emaN = "y" }
}                                 }

So I can access the values as if they were properties.

list1.First().ID    // 1
list2.First().emaN  // "x"

How can I do this?

    
asked by anonymous 22.12.2013 / 01:45

1 answer

4

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"
        }
    }
}
    
22.12.2013 / 02:43