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); }
/// <summary> /// 将List数据转换成TreeData /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">list数据源</param> /// <param name="ID">id列名</param> /// <param name="PID">父id列名</param> /// <returns></returns> public static List <dynamic> ListToTreeData <T>(List <T> source, string ID, string PID) where T : class, new() { Action <List <dynamic>, T, dynamic> AddItem = (parent, item, Recursive) => { var childrens = new List <dynamic>(); var thisitem = GenericUtil.GetDictionaryValues(item); source.FindAll(o => GenericUtil.GetValue(item, ID).Equals(GenericUtil.GetValue(o, PID))) .ForEach(subitem => { Recursive(childrens, subitem, Recursive); }); thisitem.Add("children", childrens); parent.Add(thisitem); }; var target = new List <dynamic>(); source.FindAll(m => { return(!source.Exists(n => GenericUtil.GetValue(n, ID).Equals(GenericUtil.GetValue(m, PID)))); }) .ForEach(item => AddItem(target, item, AddItem)); return(target); }