Convert DataTable to List

I have learned the previous article< Convert list < T > to DataTable>http://www.cnblogs.com/insus/p/8043173....

I have learned the previous article< Convert list < T > to DataTable>http://www.cnblogs.com/insus/p/8043173.html


In that article, we will learn to reverse and convert datatable to list < T >. This method is widely used. In many cases, the data read from the data is a DataSet or a DataTable. You need to convert them to list < T > and then to json.

Next, Insus.NET writes an extension method:

public static List<T> ToList<T>(this DataTable dt) { var dataColumn = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName).ToList(); var properties = typeof(T).GetProperties(); string columnName = string.Empty; return dt.AsEnumerable().Select(row => { var t = Activator.CreateInstance<T>(); foreach (var p in properties) { columnName = p.Name; if (dataColumn.Contains(columnName)) { if (!p.CanWrite) continue; object value = row[columnName]; Type type = p.PropertyType; if (value != DBNull.Value) { p.SetValue(t, Convert.ChangeType(value, type), null); } } } return t; }).ToList(); }
Source Code

18 May 2020, 12:12 | Views: 8281

Add new comment

For adding a comment, please log in
or create account

0 comments