C# DataTable转成List集合

本文介绍了一种将DataTable对象转换为List<T>模型集合的通用方法,解决了微信小程序API获取多条数据时的数据类型不匹配问题。通过遍历DataTable的每一行,并将各属性值映射到目标模型中,实现了数据的有效转化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发微信小程序的API获取多条数据时,会遇到返回DataTable对象的数据,但前端无法接收这个类型的数据,需要转化为List数组对象。由此,需要参考网络上的各类资料,编写了一个泛型的方法,具体代码如下:

/// <summary>
/// 将Table数据转换为List模型集合
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static IList<T> TableToListModel<T>(DataTable dt)
    where T : new()
{
    IList<T> ts = new List<T>();// 定义集合
    Type type = typeof(T); // 获得此模型的类型
    foreach (DataRow dr in dt.Rows)
    {
        T t = new T();
        PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
        foreach (PropertyInfo pi in propertys)
        {
            //获取属性名称
            String name = pi.Name;
            if (dr.Table.Columns.Contains(name))
            {
                //非泛型
                if (!pi.PropertyType.IsGenericType)
                {
                    pi.SetValue(t, string.IsNullOrEmpty(dr[name].ToString()) ? null : Convert.ChangeType(dr[name], pi.PropertyType), null);
                }
                //泛型Nullable<>
                else
                {
                    Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
                    //model属性是可为null类型,进行赋null值
                    if (genericTypeDefinition == typeof(Nullable<>))
                    {
                        //返回指定可以为 null 的类型的基础类型参数
                        pi.SetValue(t, string.IsNullOrEmpty(dr[name].ToString()) ? null : Convert.ChangeType(dr[name], Nullable.GetUnderlyingType(pi.PropertyType)), null);
                    }
                }
            }
        }
        ts.Add(t);
    }
    return ts;
} 

参考文章:[C#] DataTable转成List集合,只是这篇文章中的以下代码,无法将bigint类型的字段转化为string类型,亲测。
然后,int类型转string同理,未测。

if (value != DBNull.Value)
   pi.SetValue(t, value, null);

欢迎指正。

DataTable换成List集合是一个常见的编程任务,特别是在.NET框架中,DataTable通常用来表示内存中的数据表。下面是一个如何实现这种换的步骤说明: 1. 创建DataTable对象并填充数据。 2. 定义一个与DataTable中行结构相对应的类(Poco类)。 3. 使用反射、Linq或其他方法遍历DataTable的每一行,并将其换为Poco类的实例。 4. 将这些实例添加到List集合中。 以下是使用C#中的Linq to Dataset功能的示例代码: ```csharp using System; using System.Collections.Generic; using System.Data; using System.Linq; public class DataEntity { // 假设你的DataTable中有Name和Age两列 public string Name { get; set; } public int Age { get; set; } } public class Program { public static void Main() { // 创建一个DataTable并添加列和行数据 DataTable dt = new DataTable(); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Age", typeof(int)); dt.Rows.Add("Alice", 25); dt.Rows.Add("Bob", 22); dt.Rows.Add("Charlie", 30); // 使用Linq将DataTable换为List<DataEntity> List<DataEntity> dataList = dt.AsEnumerable() .Select(row => new DataEntity { Name = row.Field<string>("Name"), Age = row.Field<int>("Age") }) .ToList(); // 此时dataList包含了DataTable中的所有数据 } } ``` 在这个示例中,我们首先定义了一个名为`DataEntity`的类,它具有与DataTable中列对应的属性。然后我们创建了一个DataTable并添加了一些数据。使用Linq的`AsEnumerable()`方法将DataTable换为可枚举类型,然后使用`Select`方法将每一行换为`DataEntity`类的实例,并最终调用`ToList()`方法将结果换为List集合
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值