PublicStaticClasslist2datatable {#region "Convert Generic List to DataTable"///<summary>///Convert a list{t} to a DataTable.///</summary>///<typeparam name= "T" ></typeparam>///<param name= "Items" ></param>///<returns></returns>PublicStatic DataTable converttodatatable<t> (This list<t>Items) {var TB =New DataTable (typeof(T). Name); propertyinfo[] Props =typeof (T). GetProperties (BindingFlags.Public |BindingFlags.Instance);foreach (PropertyInfo propInchProps) {Type T =Getcoretype (Prop. PropertyType); Tb. Columns.Add (Prop. Name, T); }foreach (T itemInchItems) {var values =NewObject[Props. Length];for (int i =0; I < props. Length; i++) {Values[i] = Props[i]. GetValue (Item,Null); } TB. Rows.Add (values); }ReturnTb }///<summary>///Determine of specified type is nullable///</summary>///<param name= "T" ></param>///<returns></returns>PublicStaticboolIsNullable (Type t) {return!t.isvaluetype | | (T.isgenerictype && t.getgenerictypedefinition () = =typeof (Nullable<>)); }///<summary>///Return underlying type if type is Nullable otherwise return the type.///</summary>///<param name= "T" ></param>///<returns></returns>public static Type getcoretype (type T) { if (t! = null && isnullable (t)) { if (! T.isvaluetype) { return t;} else { return nullable.getunderlyingtype (t);}} else { return t;}} #endregion }
DataTable and List Interchange