How do I convert a Datatable to a dynamic object?

Asked

Viewed 954 times

2

How can I convert a DataTable in 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" }
}                                 }

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

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

How can I do this?

1 answer

4


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?

  • Take a look in that library ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.