如何将DataTable转换为动态对象?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将DataTable转换为动态对象?相关的知识,希望对你有一定的参考价值。

我如何在DataTable中转换IEnumerable<dynamicObject>

例如,我想转换任何DataTable

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

在对象列表中

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

所以

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

我该怎么做?

答案

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;
        }
    }
}

如果你想让动态行可写,你也可以尝试重写TrySetMember

用法:

  DataTable table = ...
  var dynamicTable = table.AsDynamicEnumerable();

  var firstRowsNameField = dynamicTable.First().Name;
另一答案
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;
    }
}
另一答案

以前的suneelsarraf代码仅生成运行时动态对象,其属性为字符串。以下更新将根据DataTable列的数据类型生成每个属性。

public static class DataTableExtension
{
    /// <summary>
    ///  Convert a database data table to a runtime dynamic definied type collection (dynamic class' name as table name).
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="className"></param>
    /// <returns></returns>
    public static List<dynamic> ToDynamicList(DataTable dt, string className)
    {
        return ToDynamicList(ToDictionary(dt), getNewObject(dt.Columns, className));
    }

    private static List<Dictionary<string, object>> ToDictionary(DataTable dt)
    {
        var columns = dt.Columns.Cast<DataColumn>();
        var Temp = dt.AsEnumerable().Select(dataRow => columns.Select(column =>
                             new { Column = column.ColumnName, Value = dataRow[column] })
                         .ToDictionary(data => data.Column, data => data.Value)).ToList();
        return Temp.ToList();
    }

    private static List<dynamic> ToDynamicList(List<Dictionary<string, object>> list, Type TypeObj)
    {
        dynamic temp = new List<dynamic>();
        foreach (Dictionary<string, object> step in list)
        {
            object Obj = Activator.CreateInstance(TypeObj);

            PropertyInfo[] properties = Obj.GetType().GetProperties();

            Dictionary<string, object> DictList = (Dictionary<string, object>)step;

            foreach (KeyValuePair<string, object> keyValuePair in DictList)
            {
                foreach (PropertyInfo property in properties)
                {
                    if (property.Name == keyValuePair.Key)
                    {
                        if (keyValuePair.Value != null && keyValuePair.Value.GetType() != typeof(System.DBNull))
                        {
                            if (keyValuePair.Value.GetType() == typeof(System.Guid))
                            {
                                property.SetValue(Obj, keyValuePair.Value, null);
                            }
                            else
                            {
                                property.SetValue(Obj, keyValuePair.Value, null);
                            }
                        }
                        break;
                    }
                }
            }
            temp.Add(Obj);
        }
        return temp;
    }

    private static Type getNewObject(DataColumnCollection columns, string className)
    {
        AssemblyName assemblyName = new AssemblyName();
        assemblyName.Name = "YourAssembly";
        System.Reflection.Emit.AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder module = assemblyBuilder.DefineDynamicModule("YourDynamicModule");
        TypeBuilder typeBuilder = module.DefineType(className, TypeAttributes.Public);

        foreach (DataColumn column in columns)
        {
            string propertyName = column.ColumnName;
            FieldBuilder field = typeBuilder.DefineField(propertyName, column.DataType, FieldAttributes.Public);
            PropertyBuilder property = typeBuilder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.None, column.DataType, new Type[] { column.DataType });
            MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;
            MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, column.DataType, new Type[] { column.DataType }); // Type.EmptyTypes);
            ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
            currGetIL.Emit(OpCodes.Ldarg_0);
            currGetIL.Emit(OpCodes.Ldfld, field);
            currGetIL.Emit(OpCodes.Ret);
            MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { column.DataType });
            ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
            currSetIL.Emit(OpCodes.Ldarg_0);
            currSetIL.Emit(OpCodes.Ldarg_1);
            currSetIL.Emit(OpCodes.Stfld, field);
            currSetIL.Emit(OpCodes.Ret);
            property.SetGetMethod(currGetPropMthdBldr);
            property.SetSetMethod(currSetPropMthdBldr);
        }
        Type obj = typeBuilder.CreateType();
        return obj;
    }      
}
另一答案

有一些ORM可以直接从DB读取到dynamic ExpandoObject。例如petapoco(并在这里阅读example

或者你可以尝试类似的东西:

var dt = new DataTable();

var dns = new List<dynamic>();

foreach (var item in dt.AsEnumerable())
{
    // Expando objects are IDictionary<string, object>
    IDictionary<string, object> dn = new ExpandoObject();

    foreach (var column in dt.Columns.Cast<DataColumn>())
    {
        dn[column.ColumnName] = item[column];
    }

    dns.Add(dn);
}

// Now you can do something like dns[0].MyColumnName 
// or recast to IDictionary<string, object> and do 
// something like casted["MyColumnName"]
另一答案

尝试

var MyResult = from x in MyDataTable select new { ID = x["ID"], Name = x["Name"] }.ToList ();
另一答案

将数据表转换为列表

    #region "Convert DataTable to List&l

以上是关于如何将DataTable转换为动态对象?的主要内容,如果未能解决你的问题,请参考以下文章

将 Datatable 转换为具有空值的对象

jstree做动态树,json格式传输,存储过程获得datatable之类,不知道如何把datatable转换为需要的json数据格式

VB.NET 从 DataTable 对象将表附加到数据库

如何将DataGridView转换为DataTable?

如何将DataTable转换成List<T>

如何把转换xml文件还原为原来的datatable,时间字段无法还原