Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a DataTable into a Dynamic object?

Tags:

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

For example, I want to convert any DataTable

ID | Name          DI | emaN ---------    or    ---------  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

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

How can I do it?

like image 407
BrunoLM Avatar asked Oct 17 '11 13:10

BrunoLM


People also ask

How to create dynamic object from DataTable in c#?

Using the Code NET reflection in order to be able to do it dynamically. The idea is pretty simple. Fill the object with the related field in the DataRow based on the field name, but to be able to do it smoothly, you need to have the DataTable column names match the class properties names and that's about it.

How do you create a dynamic DataTable?

Dynamic tables in Excel are the tables where when a new value is inserted into it. As a result, the table adjusts its size by itself. To create a dynamic table in Excel, we have two different methods: making a table of the data from the table section while another using the offset function.

How do you create a dynamic object?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.

How to convert a DataTable to a list in C #?

This article shows 3 ways to convert a DataTable to a List in C#. This article explains various ways to convert a DataTable to a List in C#. There are the following 3 ways to convert a DataTable to a List. Using a Loop. Using LINQ. Using a Generic Method. For this example I am creating a simple Student class like:

Is it possible to generate dynamic expandoobject from a DataTable column?

Previous suneelsarraf codes only generated runtime dynamic object with property as string. following update will generate each property based on DataTable column's data type. Show activity on this post. There are some ORMs that can read directly from DB to dynamic ExpandoObject.

How to construct the relationship between different fields in a DataTable?

There are proper ways to construct the relationship between different fields but give the class definition is done, it can be easily done by Newtonsoft.Json Process: DataSet/DataTable (Serialize) ==> Json (Deserialize) ==> Target Object List In this example as the OP, simply do: Now the DataTable is serialized into a plain string. Then do this:

How do I serialize a DataTable to a string?

Process: DataSet/DataTable (Serialize) ==> Json (Deserialize) ==> Target Object List In this example as the OP, simply do: Now the DataTable is serialized into a plain string. Then do this: List<Class1> clslist = JsonConvert.DeserializeObject<List<Class1>> (serialized, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });


2 Answers

class Program {     static void Main()     {         var dt = new DataTable();         dt.Columns.Add("ID", typeof(int));         dt.Columns.Add("Name", typeof(string));         dt.Rows.Add(1, "x");         dt.Rows.Add(2, "y");          List<dynamic> dynamicDt = dt.ToDynamic();         Console.WriteLine(dynamicDt.First().ID);         Console.WriteLine(dynamicDt.First().Name);     } }  public static class DataTableExtensions {     public static List<dynamic> ToDynamic(this DataTable dt)     {         var dynamicDt = new List<dynamic>();         foreach (DataRow row in dt.Rows)         {             dynamic dyn = new ExpandoObject();             dynamicDt.Add(dyn);             foreach (DataColumn column in dt.Columns)             {                 var dic = (IDictionary<string, object>)dyn;                 dic[column.ColumnName] = row[column];             }         }         return dynamicDt;     } } 
like image 108
Darin Dimitrov Avatar answered Sep 25 '22 16:09

Darin Dimitrov


How about with DynamicObject:

public static class DataTableX {     public static IEnumerable<dynamic> AsDynamicEnumerable(this DataTable table)     {         // Validate argument here..          return table.AsEnumerable().Select(row => new DynamicRow(row));     }      private sealed class DynamicRow : DynamicObject     {         private readonly DataRow _row;          internal DynamicRow(DataRow row) { _row = row; }          // Interprets a member-access as an indexer-access on the          // contained DataRow.         public override bool TryGetMember(GetMemberBinder binder, out object result)         {             var retVal = _row.Table.Columns.Contains(binder.Name);             result = retVal ? _row[binder.Name] : null;             return retVal;         }     } } 

You could also try overriding TrySetMember if you wish to make the dynamic-row writable.

Usage:

  DataTable table = ...   var dynamicTable = table.AsDynamicEnumerable();    var firstRowsNameField = dynamicTable.First().Name; 
like image 32
Ani Avatar answered Sep 26 '22 16:09

Ani