How to Convert DataTable to List using Reflections

前端 未结 1 1085
盖世英雄少女心
盖世英雄少女心 2020-12-03 15:58

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

相关标签:
1条回答
  • 2020-12-03 16:51

    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

    0 讨论(0)
提交回复
热议问题