惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
CXSECURITY Database RSS Feed - CXSecurity.com
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
T
Threat Research - Cisco Blogs
小众软件
小众软件
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
Apple Machine Learning Research
Apple Machine Learning Research
C
Cyber Attacks, Cyber Crime and Cyber Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
V
V2EX
博客园 - 【当耐特】
C
Cybersecurity and Infrastructure Security Agency CISA
Hugging Face - Blog
Hugging Face - Blog
The Cloudflare Blog
The Last Watchdog
The Last Watchdog
Simon Willison's Weblog
Simon Willison's Weblog
T
Threatpost
S
Secure Thoughts
O
OpenAI News
P
Proofpoint News Feed
S
SegmentFault 最新的问题
Forbes - Security
Forbes - Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Application and Cybersecurity Blog
Application and Cybersecurity Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
Scott Helme
Scott Helme
T
Tenable Blog
A
Arctic Wolf
L
LINUX DO - 热门话题
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
www.infosecurity-magazine.com
www.infosecurity-magazine.com
V
Visual Studio Blog
Hacker News: Ask HN
Hacker News: Ask HN
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
博客园 - Franky
WordPress大学
WordPress大学
Know Your Adversary
Know Your Adversary
博客园_首页
雷峰网
雷峰网
IT之家
IT之家
PCI Perspectives
PCI Perspectives
L
LINUX DO - 最新话题
H
Heimdal Security Blog

博客园 - sunwugang

026.数据库Sqlserver解决远程连接问题 C# SqlSuger 批处理自动删除指定文件夹中的文件夹以及文件 C# 开机自启动批处理bat文件 C# 将exe可执行程序设置为开机自启动 025.数据库下载&win10安装注意事项 024 数据库信息查询 + 连接串配置 C# Json操作 C# TextBox 新增文本并定位光标 C# base64转pdf + 上传至指定url C# 猜字谜 C# 闲来笔记 StringHelper--字符串左右添加指定字符 Vue学习笔记72--element ui Vue学习笔记71--histroy模式+hash模式 Vue学习笔记70--全局前置-路由守卫 + 后置路由守卫 + 独享守卫 + 组件内守卫 Vue学习笔记69--activated + deactivated Vue学习笔记68--缓存路由组件 Vue学习笔记67--编程式路由导航
C# DataTableToList
sunwugang · 2025-04-18 · via 博客园 - sunwugang

实现方式如下所示:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace HS.Helper
{
    public static class DataTableHelper
    {
        #region DataTableConvertToList 
        public static List<T> DataTableConvertToList<T>(this DataTable dataTable) where T : new()
        {
            List<T> result = new List<T>();

            // 获取目标类型的属性信息
            PropertyInfo[] properties = typeof(T).GetProperties();

            foreach (DataRow row in dataTable.Rows)
            {
                T obj = new T();

                foreach (PropertyInfo property in properties)
                {
                    // 查找 DataTable 中与属性名匹配的列
                    DataColumn column = dataTable.Columns.Cast<DataColumn>()
                        .FirstOrDefault(c => c.ColumnName.Equals(property.Name, StringComparison.OrdinalIgnoreCase));

                    if (column != null)
                    {
                        // 获取列的值
                        object value = row[column];

                        // 处理 DBNull 值
                        if (value != DBNull.Value)
                        {
                            // 根据列的类型转换值
                            Type targetType = property.PropertyType;
                            object convertedValue = ConvertValue(value, targetType);
                            property.SetValue(obj, convertedValue);
                        }
                    }
                }

                result.Add(obj);
            }

            return result;
        }

        private static object ConvertValue(object value, Type targetType)
        {
            try
            {
                // 根据目标类型进行转换
                if (targetType == typeof(int))
                    return Convert.ToInt32(value);
                else if (targetType == typeof(string))
                    return Convert.ToString(value);
                else if (targetType == typeof(double))
                    return Convert.ToDouble(value);
                else if (targetType == typeof(decimal))
                    return Convert.ToDecimal(value);
                else if (targetType == typeof(bool))
                    return Convert.ToBoolean(value);
                else if (targetType == typeof(DateTime))
                    return Convert.ToDateTime(value);
                else
                    return value; // 默认情况下返回原始值
            }
            catch
            {
                // 如果转换失败,返回默认值
                return Activator.CreateInstance(targetType);
            }
        }
        #endregion

        #region ConvertToList
        public static List<T> ConvertToList<T>(this DataTable dataTable) where T : new()
        {
            if (dataTable == null || dataTable.Rows.Count == 0)
                return new List<T>();

            // 获取目标类型的属性信息
            var properties = typeof(T).GetProperties()
                .Where(p => p.CanWrite)
                .ToList();

            // 获取 DataTable 的所有列
            //var columns = dataTable.Columns.Cast<DataColumn>();

            //foreach (var column in columns)
            //{
            //    Console.WriteLine($"Column Name: {column.ColumnName}, Type: {column.DataType}");
            //}

            var result = new List<T>();
            foreach (DataRow row in dataTable.Rows)
            {
                T item = new T();
                foreach (var property in properties)
                {
                    // 查找匹配的列名
                    var columnName = property.Name;
                    if (!dataTable.Columns.Contains(columnName))
                        continue;

                    var value = row[columnName];

                    if (value == DBNull.Value)
                    {
                        // 如果目标类型是可空类型,则设置为null
                        if (IsNullableType(property.PropertyType))
                        {
                            property.SetValue(item, null);
                        }
                        else
                        {
                            // 如果目标类型不是可空类型,则设置为默认值
                            property.SetValue(item, GetDefaultValue(property.PropertyType));
                        }
                        continue;
                    }

                    // 根据目标类型进行转换
                    if (property.PropertyType == typeof(string))
                    {
                        property.SetValue(item, Convert.ToString(value));
                    }
                    else if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
                    {
                        if (value is string stringValue)
                        {
                            if (IsStringLooksLikeInt(stringValue))
                            {
                                property.SetValue(item, Convert.ToInt32(stringValue));
                            }
                            else
                            {
                                // 如果不是整数格式,则保留为字符串
                                property.SetValue(item, stringValue);
                            }
                        }
                        else
                        {
                            property.SetValue(item, Convert.ToInt32(value));
                        }
                    }
                    else if (property.PropertyType == typeof(double) || property.PropertyType == typeof(double?))
                    {
                        property.SetValue(item, Convert.ToDouble(value));
                    }
                    else if (property.PropertyType == typeof(decimal) || property.PropertyType == typeof(decimal?))
                    {
                        property.SetValue(item, Convert.ToDecimal(value));
                    }
                    else if (property.PropertyType == typeof(bool) || property.PropertyType == typeof(bool?))
                    {
                        property.SetValue(item, Convert.ToBoolean(value));
                    }
                    else if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
                    {
                        property.SetValue(item, Convert.ToDateTime(value));
                    }
                    else
                    {
                        // 其他类型直接尝试转换
                        property.SetValue(item, Convert.ChangeType(value, property.PropertyType));
                    }
                }
                result.Add(item);
            }

            return result;
        }

        private static bool IsNullableType(Type type)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
        }

        private static object GetDefaultValue(Type type)
        {
            if (type.IsValueType)
            {
                return Activator.CreateInstance(type);
            }
            return null;
        }

        private static bool IsStringLooksLikeInt(string value)
        {
            // 检查字符串是否只包含数字
            return Regex.IsMatch(value, @"^\d+$");
        }
        #endregion

    }
}