如何将 DataTable 转换为 List<T>使用反射 [英] How to Convert DataTable to List&lt;T&gt; using Reflections

查看:24
本文介绍了如何将 DataTable 转换为 List<T>使用反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的通用列表,我使用 Reflection 和扩展方法将其自动转换为 DataTable.现在我想反向执行.我想转换 DataTable 到 List.最好说我想要帮助编写一个期望 DataTableType 并根据列自动查找该类型(类)的属性的方法为该类型(类)的对象命名并赋值.就像这个 psodu 代码:

私有列表ConvertToList(DataTable dt){列表<字符串>AllColumns =//获取数据表的所有列名for(int i=0;i

我该怎么做?

<小时>

编辑 1)

我像这样使用@Cuong Le 的回答:

var properties = typeof(CustomType).GetProperties().ToList();列表<自定义类型>list = ConvertToList(dt, properties);

和:

私有列表ConvertToList(DataTable dt,List fields) 其中 T : 类{返回 dt.AsEnumerable().Select(Convert(fields)).ToList();<------}private T Convert(DataRow row,List fields) 其中 T : 类{var 属性 = typeof(T).GetProperties().ToList();var objT = Activator.CreateInstance();foreach(属性中的var pro){pro.SetValue(objT, row[pro.Name],null);}返回对象;}

但是在一行中我在它前面放了一个箭头我得到了两个错误:

<块引用>

方法 'Convert' 没有重载需要 1 个参数

<块引用>

无法从用法推断方法System.Data.EnumerableRowCollectionExtensions.Select(System.Data.EnumerableRowCollection, System.Func)"的类型参数.尝试明确指定类型参数.

我该如何解决这个问题?

解决方案

使用AsEnumerable()方法支持LINQ:

 私人列表ConvertToList(DataTable dt){var columnNames = dt.Columns.Cast().Select(c => c.ColumnName).ToList();var 属性 = typeof(T).GetProperties();返回 dt.AsEnumerable().Select(row =>{var objT = Activator.CreateInstance();foreach(属性中的var pro){if (columnNames.Contains(pro.Name))pro.SetValue(objT, row[pro.Name]);}返回对象;}).ToList();}

<块引用>

GetProperties 使用指定的绑定约束搜索当前 Type 的属性.

这里的链接: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

这篇关于如何将 DataTable 转换为 List<T>使用反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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