123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace DAL
- {
- /// <summary>
- /// 雷怡 2021-08-17
- /// TableData List 互转
- /// </summary>
- public static class DTList
- {
- /// <summary>
- /// DataTable转换成List<T>
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="table"></param>
- /// <returns></returns>
- public static List<T> ConvertToList<T>(DataTable table)
- {
- List<T> list = new List<T>();
- T t = default(T);
- PropertyInfo[] propertypes = null;
- string tempName = string.Empty;
- foreach (DataRow row in table.Rows)
- {
- t = Activator.CreateInstance<T>();
- propertypes = t.GetType().GetProperties();
- foreach (PropertyInfo pro in propertypes)
- {
- tempName = pro.Name;
- if (table.Columns.Contains(tempName))
- {
- object value = row[tempName];
- if (!value.ToString().Equals(""))
- {
- pro.SetValue(t, value, null);
- }
- }
- }
- list.Add(t);
- }
- return list.Count == 0 ? null : list;
- }
- /// <summary>
- /// List<T>转换成DataTable
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="list">实例化当前list<T> 的list集合</param>
- /// <param name="dataList">集合数据</param>
- /// <returns>返回DataTable</returns>
- public static System.Data.DataTable ToDataTable<T>(this System.Collections.Generic.IList<T> list, System.Collections.Generic.IList<T> dataList) where T : class, new()
- {
- if (dataList == null || !dataList.Any())
- {
- return null;
- }
- Type type = typeof(T);
- System.Data.DataTable dt = new System.Data.DataTable(type.Name);
- System.Reflection.PropertyInfo[] propertyInfoArray = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
- foreach (T t in dataList.Where(t => t != null))
- {
- System.Data.DataRow row = dt.NewRow();
- for (int i = 0, j = propertyInfoArray.Length; i < j; i++)
- {
- System.Reflection.PropertyInfo propertyInfo = propertyInfoArray[i];
- string name = propertyInfo.Name;
- if (dt.Columns[name] == null)
- {
- System.Data.DataColumn column = new System.Data.DataColumn(name, propertyInfo.PropertyType);
- dt.Columns.Add(column);
- }
- row[name] = propertyInfo.GetValue(t, null);
- }
- dt.Rows.Add(row);
- }
- return dt;
- }
- }
- }
|