当前位置: 移动技术网 > IT编程>开发语言>c# > C# DataTable to List<T> based on reflection.

C# DataTable to List<T> based on reflection.

2019年12月11日  | 移动技术网IT编程  | 我要评论

from 

static class extendclass
    {
        public static list<t> todatalist<t>(this datatable dt)
        {
            var list = new list<t>();
            var plist = new list<propertyinfo>(typeof(t).getproperties());
            foreach (datarow item in dt.rows)
            {
                t s = activator.createinstance<t>();
                for (int i = 0; i < dt.columns.count; i++)
                {
                    propertyinfo info = plist.find(p => p.name == dt.columns[i].columnname);
                    if (info != null)
                    {
                        try
                        {
                            if (!convert.isdbnull(item[i]))
                            {
                                object v = null;
                                if (info.propertytype.tostring().contains("system.nullable"))
                                {
                                    v = convert.changetype(item[i], nullable.getunderlyingtype(info.propertytype));
                                }
                                else
                                {
                                    v = convert.changetype(item[i], info.propertytype);
                                }
                                info.setvalue(s, v, null);
                            }
                        }
                        catch (exception ex)
                        {
                            throw new exception("字段[" + info.name + "]转换出错," + ex.message);
                        }
                    }
                }
                list.add(s);
            }
            return list;
        }
    }

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网