DataTable 转 实体集合 List<T> (反射)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010690818/article/details/79739593
 public static class Mapper
    {
        public static IEnumerable<T> DtToModels<T>(this DataTable dt) where T : class, new()
        {
            //判断datatable是否有值
            if (dt.Columns.Count < 1 || dt.Rows.Count < 1)
            { yield break; }
            else
            {
                var propertyInfos = from propertyInfo in typeof(T).GetProperties()
                                    where dt.Columns.Contains(propertyInfo.Name)
                                    select propertyInfo;
                //循环设置属性
                foreach (DataRow dr in dt.Rows)//遍历dt中所有行
                {
                    var result = new T();
                    foreach (var p in propertyInfos)//遍历所有属性
                    {
                        try
                        {
                            if (p.PropertyType.Name == "Int64")
                            {
                                p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToInt64(dr[p.Name]), null);
                            }
                            else if (p.PropertyType.Name == "Int32")
                            {
                                p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToInt32(dr[p.Name]), null);
                            }
                            else if (p.PropertyType.Name == "Decimal")
                            {
                                p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToDecimal(dr[p.Name]), null);
                            }
                            else
                            {
                                p.SetValue(result, dr[p.Name] == DBNull.Value ? null : dr[p.Name], null);
                            }

                        }
                        catch (System.Exception)
                        {

                            throw;
                        }
                    }
                    yield return result;
                }
            }
        }


    }

使用:

猜你喜欢

转载自blog.csdn.net/u010690818/article/details/79739593