Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

c# - How can I convert a DataTable into a Dynamic object?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...