欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

DataTable转List,转对象

程序员文章站 2024-01-04 10:28:34
DataTable转List public static List ToListModel(this DataTable table) where T : new() { var type = typeof(T); var properties = type.GetProperties( ......

DataTable转List

DataTable转List,转对象
        public static List<T> ToListModel<T>(this DataTable table) where T : new()
        {
            var type = typeof(T);
            var properties = type.GetProperties();
            List<T> list = new List<T>();
            foreach (DataRow row in table.Rows)
            {
                var t = Activator.CreateInstance<T>();
                foreach (var p in properties)
                {
                    if (!table.Columns.Contains(p.Name))
                        continue;
                    if ((row[p.Name]).GetType() != typeof(DBNull))
                        p.SetValue(t, row[p.Name], null);
                }
                list.Add(t);
                t = default(T);
            }
            return list;
        }
View Code

DataTable转Object

DataTable转List,转对象
        public static object DataTableToObject(this DataTable table, int total)
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
            data.Add("total", total);
            data.Add("rows", CreateRows(table));
            return data;   
        } 

        private static object CreateRows(DataTable table)
        {
            List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
            Dictionary<string, object> childRow;
            foreach (DataRow row in table.Rows)
            {
                childRow = new Dictionary<string, object>();
                foreach (DataColumn col in table.Columns)
                {
                    bool isDate = false;                    
                    #region 时间转化
                    if (col.ColumnName.Contains("_DATE") || col.ColumnName.Contains("_TIME") || col.ColumnName.Contains("_DT") || col.ColumnName.Contains("FDATE"))
                    {
                        isDate = true;
                    }                 
                    #endregion
                    if (isDate)
                    {
                        try
                        {
                            childRow.Add(col.ColumnName, row[col] is DBNull ? "" : Convert.ToDateTime(row[col]).ToString("yyyy-MM-dd"));
                        }
                        catch
                        {
                            childRow.Add(col.ColumnName, row[col]);
                        }
                    }
                    else {
                        childRow.Add(col.ColumnName, row[col]);
                    }
                }
                parentRow.Add(childRow);
            }
            return parentRow;
        } 
View Code

 

上一篇:

下一篇: