(精華)2020年6月26日 C#類庫 DataTable(擴充套件方法)

愚公搬程式碼發表於2020-06-26
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;

namespace Core.Util
{
    public static partial class Extention
    {
        /// <summary>
        /// DataTable轉List
        /// </summary>
        /// <typeparam name="T">轉換型別</typeparam>
        /// <param name="dt">資料來源</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt)
        {
            List<T> list = new List<T>();

            //確認引數有效,若無效則返回Null
            if (dt == null)
                return list;
            else if (dt.Rows.Count == 0)
                return list;

            Dictionary<string, string> dicField = new Dictionary<string, string>();
            Dictionary<string, string> dicProperty = new Dictionary<string, string>();
            Type type = typeof(T);

            //建立欄位字典,方便查詢欄位名
            type.GetFields().ForEach(aFiled =>
            {
                dicField.Add(aFiled.Name.ToLower(), aFiled.Name);
            });

            //建立屬性字典,方便查詢屬性名
            type.GetProperties().ForEach(aProperty =>
            {
                dicProperty.Add(aProperty.Name.ToLower(), aProperty.Name);
            });

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //建立泛型物件
                T _t = Activator.CreateInstance<T>();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string memberKey = dt.Columns[j].ColumnName.ToLower();

                    //欄位賦值
                    if (dicField.ContainsKey(memberKey))
                    {
                        FieldInfo theField = type.GetField(dicField[memberKey]);
                        var dbValue = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                            dbValue = null;
                        if (dbValue != null)
                        {
                            Type memberType = theField.FieldType;
                            dbValue = dbValue.ChangeType_ByConvert(memberType);
                        }
                        theField.SetValue(_t, dbValue);
                    }
                    //屬性賦值
                    if (dicProperty.ContainsKey(memberKey))
                    {
                        PropertyInfo theProperty = type.GetProperty(dicProperty[memberKey]);
                        var dbValue = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                            dbValue = null;
                        if (dbValue != null)
                        {
                            Type memberType = theProperty.PropertyType;
                            dbValue = dbValue.ChangeType_ByConvert(memberType);
                        }
                        theProperty.SetValue(_t, dbValue);
                    }
                }
                list.Add(_t);
            }
            return list;
        }

        /// <summary>
        ///將DataTable轉換為標準的CSV字串
        /// </summary>
        /// <param name="dt">資料表</param>
        /// <returns>返回標準的CSV</returns>
        public static string ToCsvStr(this DataTable dt)
        {
            //以半形逗號(即,)作分隔符,列為空也要表達其存在。
            //列內容如存在半形逗號(即,)則用半形引號(即"")將該欄位值包含起來。
            //列內容如存在半形引號(即")則應替換成半形雙引號("")轉義,並用半形引號(即"")將該欄位值包含起來。
            StringBuilder sb = new StringBuilder();
            DataColumn colum;
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    colum = dt.Columns[i];
                    if (i != 0) sb.Append(",");
                    if (colum.DataType == typeof(string) && row[colum].ToString().Contains(","))
                    {
                        sb.Append("\"" + row[colum].ToString().Replace("\"", "\"\"") + "\"");
                    }
                    else sb.Append(row[colum].ToString());
                }
                sb.AppendLine();
            }

            return sb.ToString();
        }
    }
}

相關文章