利用反射把简单的匿名类对象集合转换成表格
public static class ExtendMethod { public static DataTable SimpleLinqToTable<T>(this IEnumerable<T> collection) { DataTable dt = new DataTable(); if (collection.Count() <= 0) { return dt; } PropertyInfo[] pros = collection.First().GetType().GetProperties(); foreach (PropertyInfo pro in pros) { string columnName = pro.Name; Type type = pro.PropertyType; dt.Columns.Add(columnName, type); } IEnumerator<T> col = collection.GetEnumerator(); while (col.MoveNext()) { T obj = col.Current; PropertyInfo[] tpros = obj.GetType().GetProperties(); List<object> objs = new List<object>(); foreach (PropertyInfo pro in pros) { objs.Add(pro.GetValue(obj, null)); } dt.Rows.Add(objs.ToArray()); } return dt; } }
时间: 2024-10-25 04:40:49