C# · 12月 22, 2021

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



我用@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.