C# DataTable转成List集合

在开发微信小程序的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);

欢迎指正。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值