- public static class DataTableExtensions
- {
-
-
-
-
-
-
-
-
-
- public static DataTable ToDataTable<T>(this IEnumerable<T> list)
- {
-
-
- List<PropertyInfo> pList = new List<PropertyInfo>();
-
-
- Type type = typeof(T);
- DataTable dt = new DataTable();
-
- Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
- foreach (var item in list)
- {
-
- DataRow row = dt.NewRow();
-
- pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
-
- dt.Rows.Add(row);
- }
- return dt;
- }
-
-
-
-
-
-
-
-
- public static List<T> ToList<T>(this DataTable dt) where T : class, new()
- {
-
- List<PropertyInfo> prlist = new List<PropertyInfo>();
-
-
- Type t = typeof(T);
-
-
- Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
-
-
-
- List<T> oblist = new List<T>();
-
- foreach (DataRow row in dt.Rows)
- {
-
- T ob = new T();
-
- prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
-
- oblist.Add(ob);
- }
- return oblist;
- }
-
-
-
-
-
-
-
-
-
- public static DataTable ToDataTableTow(IList list)
- {
- DataTable result = new DataTable();
- if (list.Count > 0)
- {
- PropertyInfo[] propertys = list[0].GetType().GetProperties();
-
- foreach (PropertyInfo pi in propertys)
- {
- result.Columns.Add(pi.Name, pi.PropertyType);
- }
- for (int i = 0; i < list.Count; i++)
- {
- ArrayList tempList = new ArrayList();
- foreach (PropertyInfo pi in propertys)
- {
- object obj = pi.GetValue(list[i], null);
- tempList.Add(obj);
- }
- object[] array = tempList.ToArray();
- result.LoadDataRow(array, true);
- }
- }
- return result;
- }
-
-
-
-
-
-
-
-
-
-
-
-
- public static DataTable ToDataTable<T>(IList<T> list)
- {
- return ToDataTable<T>(list, null);
-
- }
-
-
-
-
-
-
-
-
-
-
-
- public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
- {
- List<string> propertyNameList = new List<string>();
- if (propertyName != null)
- propertyNameList.AddRange(propertyName);
- DataTable result = new DataTable();
- if (list.Count > 0)
- {
- PropertyInfo[] propertys = list[0].GetType().GetProperties();
- foreach (PropertyInfo pi in propertys)
- {
- if (propertyNameList.Count == 0)
- {
- result.Columns.Add(pi.Name, pi.PropertyType);
- }
- else
- {
- if (propertyNameList.Contains(pi.Name))
- result.Columns.Add(pi.Name, pi.PropertyType);
- }
- }
-
- for (int i = 0; i < list.Count; i++)
- {
- ArrayList tempList = new ArrayList();
- foreach (PropertyInfo pi in propertys)
- {
- if (propertyNameList.Count == 0)
- {
- object obj = pi.GetValue(list[i], null);
- tempList.Add(obj);
- }
- else
- {
- if (propertyNameList.Contains(pi.Name))
- {
- object obj = pi.GetValue(list[i], null);
- tempList.Add(obj);
- }
- }
- }
- object[] array = tempList.ToArray();
- result.LoadDataRow(array, true);
- }
- }
- return result;
- }
- }