DataTable和List相互转换及根据实体类生成DataTable结构功能实现

在我们开发过程中,需要用到DataTable和List集合相互转换功能,当然我也不例外。

避免重复造轮子,所以把这功能记录下来

泛型集合转换成DataTable:

/// <summary>
/// 泛型集合转DataTable
/// </summary>
/// <typeparam name="T">集合类型</typeparam>
/// <param name="entityList">泛型集合</param>
/// <returns>DataTable</returns>
public DataTable ListToDataTable<T>(IList<T> entityList)
{
    if (entityList == null) return null;
    DataTable dt = CreateTable<T>();
    Type entityType = typeof(T);
    //PropertyInfo[] properties = entityType.GetProperties();
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
    foreach (T item in entityList)
    {
        DataRow row = dt.NewRow();
        foreach (PropertyDescriptor property in properties)
        {
            row[property.Name] = property.GetValue(item);
        }
        dt.Rows.Add(row);
    }

    return dt;
}


DataTable转换成List集合:

/// <summary>
/// DataTable转List集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public List<T> DataTableToList<T>(DataTable dt) where T : new()
{
    if (dt == null) return null;
    List<T> entityList = new List<T>();
    List<string> columnList = new List<string>();
    if (dt.Columns.Count > 0)
    {
        columnList.AddRange(from DataColumn column in dt.Columns select column.ColumnName);
    }
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

    foreach (DataRow row in dt.Rows)
    {
        var entity = new T();
        foreach (var column in columnList)
        {
            var proper = properties.Find(column, true);
            if (proper != null)
            {
                var properType = proper.PropertyType;
                if (proper.Converter != null)
                {
                    object value = null;
                    var type = proper.PropertyType;
                    if (type == typeof (string))
                    {
                        value = row[column].ToString();
                    }
                    else if(type == typeof(decimal))
                    {
                        value = decimal.Parse(row[column].ToString());
                    }
                    else if (type == typeof (decimal?))
                    {
                        if (row[column] != null)
                        {
                            value = decimal.Parse(row[column].ToString());
                        }
                    }
                    else
                    {
                        value = proper.Converter.ConvertTo(row[column], properType);
                    }
                    if (value != null)
                        proper.SetValue(entity, value);
                }
            }
        }
        entityList.Add(entity);
    }
    return entityList;
}


根据实体类生成DataTable结构:

/// <summary>
/// 根据实体类生成DataTable结构
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
private DataTable CreateTable<T>()
{
    Type entityType = typeof(T);
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
    //生成DataTable的结构
    DataTable dt = new DataTable();
    foreach (PropertyDescriptor prop in properties)
    {
        dt.Columns.Add(prop.Name);
        dt.Columns[prop.Name].DataType = prop.PropertyType;
    }
    return dt;
}


我们可以把他们写到一起封装成一个数据转换帮助类 DataConvertUtil :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace demo1
{
    public class DataConvertUtil
    {
        /// <summary>
        /// 泛型集合转DataTable
        /// </summary>
        /// <typeparam name="T">集合类型</typeparam>
        /// <param name="entityList">泛型集合</param>
        /// <returns>DataTable</returns>
        public static DataTable ListToDataTable<T>(IList<T> entityList)
        {
            if (entityList == null) return null;
            DataTable dt = CreateTable<T>();
            Type entityType = typeof(T);
            //PropertyInfo[] properties = entityType.GetProperties();
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
            foreach (T item in entityList)
            {
                DataRow row = dt.NewRow();
                foreach (PropertyDescriptor property in properties)
                {
                    row[property.Name] = property.GetValue(item);
                }
                dt.Rows.Add(row);
            }

            return dt;
        }

        /// <summary>
        /// 根据实体类生成DataTable结构
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private static DataTable CreateTable<T>()
        {
            Type entityType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
            //生成DataTable的结构
            DataTable dt = new DataTable();
            foreach (PropertyDescriptor prop in properties)
            {
                dt.Columns.Add(prop.Name);
                dt.Columns[prop.Name].DataType = prop.PropertyType;
            }
            return dt;
        }

        /// <summary>
        /// DataTable转List集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {
            if (dt == null) return null;
            List<T> entityList = new List<T>();
            List<string> columnList = new List<string>();
            if (dt.Columns.Count > 0)
            {
                columnList.AddRange(from DataColumn column in dt.Columns select column.ColumnName);
            }
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

            foreach (DataRow row in dt.Rows)
            {
                var entity = new T();
                foreach (var column in columnList)
                {
                    var proper = properties.Find(column, true);
                    if (proper != null)
                    {
                        var properType = proper.PropertyType;
                        if (proper.Converter != null)
                        {
                            object value = null;
                            var type = proper.PropertyType;
                            if (type == typeof (string))
                            {
                                value = row[column].ToString();
                            }
                            else if(type == typeof(decimal))
                            {
                                value = decimal.Parse(row[column].ToString());
                            }
                            else if (type == typeof (decimal?))
                            {
                                if (row[column] != null)
                                {
                                    value = decimal.Parse(row[column].ToString());
                                }
                            }
                            else
                            {
                                value = proper.Converter.ConvertTo(row[column], properType);
                            }
                            if (value != null)
                                proper.SetValue(entity, value);
                        }
                    }
                }
                entityList.Add(entity);
            }
            return entityList;
        }
    }
}



版权声明:若无特殊注明,本文为《奕独客》原创,转载请保留文章出处。
本文链接:DataTable和List相互转换及根据实体类生成DataTable结构功能实现 [https://www.yiduk.com/教程资料/23.html]
正文到此结束

热门推荐