五维思考

学习要加,骄傲要减,机会要乘,懒惰要除。 http://www.5dthink.cn

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1、泛型方法(1)

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

/// <summary>
/// 将DataTable数据源转换成实体类
/// </summary>
/// <typeparam name="T">实体</typeparam>
public static class ToModel<T> where T : new()
{
    /// <summary>
    /// 将DataTable数据源转换成实体类
    /// </summary>
    public static List<T> ConvertToModel(DataTable dt)
    {
        List<T> ts = new List<T>();
        foreach (DataRow dr in dt.Rows)
        {
            T t = new T();
            PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
            foreach (PropertyInfo pi in propertys)
            {
                if (dt.Columns.Contains(pi.Name))
                {
                    if (!pi.CanWrite) continue;
                    var value = dr[pi.Name];
                    if (value != DBNull.Value)
                    {
                        switch (pi.PropertyType.FullName)
                        {
                            case "System.Decimal":
                                pi.SetValue(t, decimal.Parse(value.ToString()), null);
                                break;
                            case "System.String":
                                pi.SetValue(t, value.ToString(), null);
                                break;
                            case "System.Int32":
                                pi.SetValue(t, int.Parse(value.ToString()), null);
                                break;
                            default:
                                pi.SetValue(t, value, null);
                                break;
                        }
                    }
                }
            }
            ts.Add(t);
        }
        return ts;
    }
}

2、泛型方法(2)

public static T GetEntity<T>(DataTable table) where T : new()
{
	T entity = new T();
	foreach (DataRow row in table.Rows)
	{
		foreach (var item in entity.GetType().GetProperties())
		{
			if (row.Table.Columns.Contains(item.Name))
			{
				if (DBNull.Value != row[item.Name])
				{
					item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
				}
			}
		}
	}
	return entity;
}

public static IList<T> GetEntities<T>(DataTable table) where T : new()
{
	IList<T> entities = new List<T>();
	foreach (DataRow row in table.Rows)
	{
		T entity = new T();
		foreach (var item in entity.GetType().GetProperties())
		{
			item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
		}
		entities.Add(entity);
	}
	return entities;
}

3、泛型+扩展方法(1)

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace DotNet
{
    public static class ExtendClass
    {
        public static IEnumerable<T> ToEntitys<T>(this DataTable dt) where T : new()
        {
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
            List<T> list = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T entity = (default(T) == null) ? Activator.CreateInstance<T>() : default(T);
                PropertyInfo[] array = properties;
                for (int i = 0; i < array.Length; i++)
                {
                    PropertyInfo property = array[i];
                    if (dt.Columns.Contains(property.Name))
                    {
                        Type valueType = property.PropertyType;
                        property.SetValue(entity, Convert.ChangeType(dr[property.Name], valueType), null);
                    }
                }
                FieldInfo[] array2 = fields;
                for (int j = 0; j < array2.Length; j++)
                {
                    FieldInfo field = array2[j];
                    if (dt.Columns.Contains(field.Name))
                    {
                        Type valueType2 = field.FieldType;
                        field.SetValue(entity, Convert.ChangeType(dr[field.Name], valueType2));
                    }
                }
                list.Add(entity);
            }
            return list;
        }
    }
}

扩展方法使用:

DataTable dt = GetTable();
var list = dt.ToEntitys<MyEntitie>();

4、泛型+扩展方法(2)

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

namespace DotNet
{
    public static class ExtendClass
    {
        /// <summary>
        /// DataRow扩展方法:将DataRow类型转化为指定类型的实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <returns></returns>
        public static T ToModel<T>(this DataRow dr) where T : class, new()
        {
            return ToModel<T>(dr, true);
        }

        /// <summary>
        /// DataRow扩展方法:将DataRow类型转化为指定类型的实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="dateTimeToString">是否需要将日期转换为字符串,默认为转换,值为true</param>
        /// <returns></returns>
        /// <summary>
        public static T ToModel<T>(this DataRow dr, bool dateTimeToString) where T : class, new()
        {
            if (dr != null)
                return ToList<T>(dr.Table, dateTimeToString).First();
            return null;
        }
    
        /// <summary>
        /// DataTable扩展方法:将DataTable类型转化为指定类型的实体集合
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="dateTimeToString">是否需要将日期转换为字符串,默认为转换,值为true</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt, bool dateTimeToString) where T : class, new()
        {
            List<T> list = new List<T>();
            if (dt != null)
            {
                List<PropertyInfo> infos = new List<PropertyInfo>();
                Array.ForEach<PropertyInfo>(typeof(T).GetProperties(), p =>
                {
                    if (dt.Columns.Contains(p.Name))
                    {
                        infos.Add(p);
                    }
                });
                SetList<T>(list, infos, dt, dateTimeToString);
            }
            return list;
        }
    
        private static void SetList<T>(List<T> list, List<PropertyInfo> infos, DataTable dt, bool dateTimeToString) where T : class, new()
        {
            foreach (DataRow dr in dt.Rows)
            {
                T model = new T();
                infos.ForEach(p =>
                {
                    if (dr[p.Name] != DBNull.Value)
                    {
                        object tempValue = dr[p.Name];
                        if (dateTimeToString && dr[p.Name].GetType() == typeof(DateTime))
                            tempValue = dr[p.Name].ToString();
                        try
                        {
                            p.SetValue(model, tempValue, null);
                        }
                        catch { }
                    }
                });
                list.Add(model);
            }
        }
    }

}
posted on 2019-03-27 12:46  五维思考  阅读(1904)  评论(0编辑  收藏  举报

QQ群:1. 全栈码农【346906288】2. VBA/VSTO【2660245】