微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何使用Reflections将DataTable转换为List

我有一个类的通用列表,我使用反射和扩展方法自动将其转换为DataTable.现在我想反向执行.我想将DataTable转换为List.Better说我想要帮助写一个方法期望一个DataTable和一个Type,并根据列名自动查找该类型(类)的属性,并为该Type(类)的对象赋值.就像这个psodu代码
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
        }
    }
}

我怎么能这样做?

编辑1)

我用@Cuong Le的回答是这样的:

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

并且:

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

但是在排队中我在它前面放了一个箭头我得到了这两个错误

No overload for method ‘Convert’ takes 1 arguments

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.

我怎么能解决这个问题?

解决方法

使用AsEnumerable()方法支持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.

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

原文地址:https://www.jb51.cc/csharp/91271.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐