public static Dictionary <string, Type> GetListProperties(dynamic list) { var type = GenericUtil.GetGenericType(list); var names = new Dictionary <string, Type>(); if (GenericUtil.IsDynamicType(type)) { if (list.Count > 0) { foreach (var item in GenericUtil.GetDictionaryValues(list[0])) { names.Add(item.Key, (item.Value ?? string.Empty).GetType()); } } } else { foreach (var p in ReflectionUtil.GetProperties(type)) { names.Add(p.Value.Name, p.Value.PropertyType); } } return(names); }
public static DataTable ListToDataTable(object datas, string tableName) { Type type = GenericUtil.GetGenericType(datas); if (string.IsNullOrEmpty(tableName)) { tableName = type.Name; } DataTable table = new DataTable(tableName); table.BeginLoadData(); var properties = ReflectionUtil.GetProperties(type); foreach (var p in properties) { Type colType = p.Value.PropertyType; string typeName = colType.ToString(); if (colType.IsGenericType) { typeName = colType.GetGenericArguments()[0].ToString(); } Type newType = Type.GetType(typeName, false); if (newType != null) { table.Columns.Add(p.Value.Name, newType); } } IEnumerator enumerator = ((dynamic)datas).GetEnumerator(); while (enumerator.MoveNext()) { DataRow row = table.NewRow(); foreach (var p in properties) { var value = GenericUtil.GetValue(enumerator.Current, p.Value.Name); if ((Type.GetType(p.Value.PropertyType.ToString(), false) != null) && (value != null)) { row[p.Value.Name] = value; } } table.Rows.Add(row); } table.EndLoadData(); table.AcceptChanges(); return(table); }