集合操作类
后端将指定的集合转换成DataTable
ListExtensions.cs
1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using System.Data; 5 using System.Linq; 6 using System.Reflection; 7 using System.Text; 8 using System.Threading.Tasks; 9 10 namespace SH3H.NC.Common.ConvertHelper 11 { 12 public static class ListExtensions 13 { 14 /// <summary> 15 /// 将指定的集合转换成DataTable。 16 /// </summary> 17 /// <param name="list">将指定的集合。</param> 18 /// <returns>返回转换后的DataTable。</returns> 19 public static DataTable ToDataTable(this IList list) 20 { 21 DataTable table = new DataTable(); 22 if (list.Count > 0) 23 { 24 PropertyInfo[] propertys = list[0].GetType().GetProperties(); 25 foreach (PropertyInfo pi in propertys) 26 { 27 Type pt = pi.PropertyType; 28 if ((pt.IsGenericType) && (pt.GetGenericTypeDefinition() == typeof(Nullable<>))) 29 { 30 pt = pt.GetGenericArguments()[0]; 31 } 32 table.Columns.Add(new DataColumn(pi.Name, pt)); 33 } 34 35 for (int i = 0; i < list.Count; i++) 36 { 37 ArrayList tempList = new ArrayList(); 38 foreach (PropertyInfo pi in propertys) 39 { 40 object obj = pi.GetValue(list[i], null); 41 tempList.Add(obj); 42 } 43 object[] array = tempList.ToArray(); 44 table.LoadDataRow(array, true); 45 } 46 } 47 return table; 48 } 49 50 public static DataTable ToDataTable<T>(this List<T> list, List<string> ignoreNames=null) 51 { 52 DataTable table = new DataTable() {TableName= Activator.CreateInstance<T>().GetType().Name }; 53 //创建列头 54 PropertyInfo[] propertys = typeof(T).GetProperties(); 55 foreach (PropertyInfo pi in propertys) 56 { 57 if (ignoreNames != null && ignoreNames.Contains(pi.Name)) 58 { 59 continue; 60 } 61 Type pt = pi.PropertyType; 62 if ((pt.IsGenericType) && (pt.GetGenericTypeDefinition() == typeof(Nullable<>))) 63 { 64 pt = pt.GetGenericArguments()[0]; 65 } 66 table.Columns.Add(new DataColumn(pi.Name, pt)); 67 } 68 //创建数据行 69 if (list.Count > 0) 70 { 71 for (int i = 0; i < list.Count; i++) 72 { 73 ArrayList tempList = new ArrayList(); 74 foreach (PropertyInfo pi in propertys) 75 { 76 if (ignoreNames != null && ignoreNames.Contains(pi.Name)) 77 { 78 continue; 79 } 80 object obj = pi.GetValue(list[i], null); 81 tempList.Add(obj); 82 } 83 object[] array = tempList.ToArray(); 84 table.LoadDataRow(array, true); 85 } 86 } 87 return table; 88 } 89 } 90 }
调用
1 public async override Task DataBuild() 2 { 3 DataBuildSet = new DataSet("FormData"); 4 var projectInfoList = new List<T_ProjectInfo>() { ProjectInfo }; 5 DataBuildSet.Tables.Add(ListExtensions.ToDataTable(projectInfoList)); 6 }
我佛真的不渡哈批

浙公网安备 33010602011771号