如何转换数据表中列出< T>用思考 [英] How to Convert DataTable to List<T> using Reflections

查看:178
本文介绍了如何转换数据表中列出< T>用思考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的泛型列表,我自动使用反射和延伸methods.Now我想这样做反向direction.I转换为DataTable的希望转换数据表来List.Better说我需要帮助编写期望的方法的数据表键入,并根据列名自动发现,类型(类)的属性,并指定值类型(类)。像这种psodu代码的对象:

 私人列表< T> ConvertToList< T>(DataTable的DT)
{
名单,LT;字符串> AllColumns = //获取一个DataTable
为所有列名(INT I = 0; I< dt.Rows.Count;我++)
{
的foreach(在AllColumns VAR项)
{
//获取属性根据** **项
//获取数据行[一] [项目]并将其分配给T.property
}
}
}

我怎样才能做到这一点?






修改1)



我用@Cuong乐一样的回答这样的:

  VAR性能= typeof运算(CustomType).GetProperties()了ToList(); 
名单,LT; CustomType>列表= ConvertToList< CustomType>(DT,属性);

 私人列表< T> ConvertToList< T>(DataTable的DT,表<的PropertyInfo>字段),其中T:一流
{
返回dt.AsEnumerable()选择(转换< T>(场))了ToList(); < ------
}

私人牛逼转换< T>(DataRow的行列表与LT;的PropertyInfo>字段),其中T:类
{
VAR性能= typeof运算(T).GetProperties()了ToList()。

VAR objT = Activator.CreateInstance< T>();
的foreach(在性能VAR PRO)
{
pro.SetValue(objT,行[pro.Name],NULL);
}

返回objT;
}



但在网上我把箭头在前面我这两个错误




没有过载方法'转换'需要1个参数







的类型参数的方法System.Data.EnumerableRowCollectionExtensions.Select(System.Data.EnumerableRowCollection,系统.FUNC)'不能从使用推断。请尝试显式指定类型参数。




我该如何解决这个问题呢?


解决方案

使用 AsEnumerable()方法来支持LINQ:

 私人列表< T> ConvertToList< T>(DataTable的DT)
{
VAR COLUMNNAMES = dt.Columns.Cast< D​​ataColumn的>()
。选择(C => c.ColumnName)
。了ToList();

VAR性能= typeof运算(T).GetProperties();

返回dt.AsEnumerable()选择(行=方式>
{
VAR objT = Activator.CreateInstance< T>();

的foreach(在性能VAR PRO)
{
如果(columnNames.Contains(pro.Name))
pro.SetValue(objT,行[pro.Name]);
}

返回objT;
})了ToList();

}




的GetProperties 搜索当前类型的属性,使用指定绑定约束。




在链接在这里: http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx


I have a Generic list of a class that I automatically convert it to DataTable using Reflection and extension methods.Now I want to do it in reverse direction.I want to convert DataTable to List.Better to say I want help to write a method that expect a DataTable and a Type and automatically find property of that type(class) according to column name and assign value to object of that Type(class).like this psodu code:

private List<T> ConvertToList<T>(DataTable dt)
{
    List<string> AllColumns = // Get All Column Names of a DataTable
    for(int i=0;i<dt.Rows.Count;i++)
    {
        foreach(var item in AllColumns )
        {
             //Get Property According To **ITEM**
             //Get Data Of Rows[i][item] and assign it to T.property
        }
    }
}

How I can do this?


Edit 1)

I use answer of @Cuong Le like this:

var properties = typeof(CustomType).GetProperties().ToList();
List<CustomType> list = ConvertToList<CustomType>(dt, properties);

and :

private List<T> ConvertToList<T>(DataTable dt,List<PropertyInfo> fields) where T : class
{
    return dt.AsEnumerable().Select(Convert<T>(fields)).ToList();  <------
}

private T Convert<T>(DataRow row,List<PropertyInfo> fields) where T : class
{
    var properties = typeof(T).GetProperties().ToList();

    var objT = Activator.CreateInstance<T>();
    foreach (var pro in properties)
    {
        pro.SetValue(objT, row[pro.Name],null);
    }

    return objT;
} 

but in line I place an arrow in front of it I got this two errors:

No overload for method 'Convert' takes 1 arguments

and

The type arguments for method 'System.Data.EnumerableRowCollectionExtensions.Select(System.Data.EnumerableRowCollection, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How I can solve this problem?

解决方案

Use AsEnumerable() method to support LINQ:

    private List<T> ConvertToList<T>(DataTable dt)
    {
        var columnNames = dt.Columns.Cast<DataColumn>()
            .Select(c => c.ColumnName)
            .ToList();

        var properties = typeof(T).GetProperties();

        return dt.AsEnumerable().Select(row =>
            {
                var objT = Activator.CreateInstance<T>();

                foreach (var pro in properties)
                {
                    if (columnNames.Contains(pro.Name))
                        pro.SetValue(objT, row[pro.Name]);
                }

                return objT;
            }).ToList();

    }

GetProperties searches for the properties of the current Type, using the specified binding constraints.

The link in here: http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx

这篇关于如何转换数据表中列出&LT; T&GT;用思考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆