zoukankan      html  css  js  c++  java
  • C#中DataTable转换List和List再转为DataTable,以及DataRow转为实体对象

    C#中DataTable转换List和List再转为DataTable,以及DataRow转为实体对象等,都是网上找的,有些也有错误

    ModelConvertHelper.cs

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Bxlz.Common
    {
        /// <summary>    
        /// 实体转换辅助类    
        /// </summary>    
        public class ModelConvertHelper<T> where T : new()
        {
            public static IList<T> ConvertToModel(DataTable dt)
            {
                // 定义集合    
                IList<T> ts = new List<T>();
    
                // 获得此模型的类型   
                Type type = typeof(T);
                string tempName = "";
    
                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    // 获得此模型的公共属性      
                    PropertyInfo[] propertys = t.GetType().GetProperties();
                    foreach (PropertyInfo pi in propertys)
                    {
                        tempName = pi.Name;  // 检查DataTable是否包含此列    
    
                        if (dt.Columns.Contains(tempName))
                        {
                            // 判断此属性是否有Setter      
                            if (!pi.CanWrite) continue;
    
                            object value = dr[tempName];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                    ts.Add(t);
                }
                return ts;
            }
    
    
            /// <summary>
            /// 这个方法有时转换会出现“System.NotSupportedException” : DataSet 不支持 System.Nullable<>/// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="collection"></param>
            /// <returns></returns>
            public static DataTable ConvertToDataTable<T>(IEnumerable<T> collection)
            {
                var props = typeof(T).GetProperties();
                var dt = new DataTable();
                dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
                if (collection.Count() > 0)
                {
                    for (int i = 0; i < collection.Count(); i++)
                    {
                        ArrayList tempList = new ArrayList();
                        foreach (PropertyInfo pi in props)
                        {
                            object obj = pi.GetValue(collection.ElementAt(i), null);
                            tempList.Add(obj);
                        }
                        object[] array = tempList.ToArray();
                        dt.LoadDataRow(array, true);
                    }
                }
                return dt;
            }
    
    
    
    
            public static DataTable ToDataTable<T>(IList<T> list)
            {
                return ToDataTable(list, null);
            }
    
            //将list转换成DataTable
            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)
                        {
                            //if (DBNull.Value.Equals(pi.PropertyType))
                            //{
                            //   // pi.PropertyType = DateTime;
                            //}
                            Type colType = pi.PropertyType;
                            if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
                            {
                                colType = colType.GetGenericArguments()[0];
                            }
                            result.Columns.Add(pi.Name, colType);
                            //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;
            }
    
    
            #region----DataTable转模型的另一种方法-----
    
            public static List<T> GetModelFromDB<T>(DataTable dt)
            {
                List<T> data = new List<T>();
                foreach (DataRow row in dt.Rows)
                {
                    T item = GetItem<T>(row);
                    data.Add(item);
                }
                return data;
            }
    
            /// <summary>
            /// 将DataRow转换成实体对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="dr"></param>
            /// <returns></returns>
            public static T GetItem<T>(DataRow dr)
            {
                try
                {
                    Type temp = typeof(T);
                    T obj = Activator.CreateInstance<T>();
                    foreach (DataColumn column in dr.Table.Columns)
                    {
                        foreach (PropertyInfo pro in temp.GetProperties())
                        {
                            if (pro.Name.ToLower() == column.ColumnName.ToLower())
                            {
                                if (dr[column.ColumnName] == DBNull.Value)
                                {
                                    pro.SetValue(obj, " ", null);
                                    break;
                                }
                                else
                                {
                                    pro.SetValue(obj, dr[column.ColumnName], null);
                                    break;
                                }
                            }
                        }
                    }
                    return obj;
                }
               catch(Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
    
            #endregion
    
        }   
    
    }

    简单使用:

                //3.执行sql
                DataSet ds = AccessHelper.Query(strSql.ToString());
        
                DataTable dt = ds.Tables[0];
                //DataTable转List
                List<GoodsData> list = Bxlz.Common.ModelConvertHelper<GoodsData>.ConvertToModel(dt).ToList();
    
                foreach (var good in list)
                {
                    string str = JsonConvert.SerializeObject(good);//把对象转换为JSON字符串
                    Console.WriteLine(str);
                }
    //List转DataTable DataTable dt1 = Bxlz.Common.ModelConvertHelper<GoodsData>.ToDataTable<GoodsData>(list); foreach (DataRow val in dt1.Rows) { Console.WriteLine("----={0}=---={1}=---={2}=---={3}=", val["uid"], val[1], val[2], val[4]); }

    部分参考:

    https://www.cnblogs.com/slu182/p/4383673.html 

  • 相关阅读:
    973. K Closest Points to Origin
    919. Complete Binary Tree Inserter
    993. Cousins in Binary Tree
    20. Valid Parentheses
    141. Linked List Cycle
    912. Sort an Array
    各种排序方法总结
    509. Fibonacci Number
    374. Guess Number Higher or Lower
    238. Product of Array Except Self java solutions
  • 原文地址:https://www.cnblogs.com/fps2tao/p/14707576.html
Copyright © 2011-2022 走看看