using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Ewide.Core.Util
{
    public static class TypeHelper
    {
        /// <summary>
        /// 动态创建List<?> 泛型
        /// </summary>
        /// <param name="t">Type类</param>
        /// <param name="items">数据源</param>
        /// <returns></returns>
        public static object MakeList(this Type t, params object[] items)
        {
            Type type = typeof(List<>).MakeGenericType(t);
            object list = Activator.CreateInstance(type);
            System.Collections.IList ilist = list as System.Collections.IList;
            foreach (object o in items)
                ilist.Add(o);
            return list;
        }
        /// <summary>
        /// 动态创建List<?> 泛型
        /// </summary>
        /// <param name="t">Type类</param>
        /// <param name="objList">数据源</param>
        /// <returns></returns>
        public static object MakeList(this Type t, Object objList)
        {
            Type type = typeof(List<>).MakeGenericType(t);
            object list = Activator.CreateInstance(type);
            System.Collections.IList ilist = list as System.Collections.IList;
            var collection = objList as System.Collections.IEnumerable;
            if (collection != null)
            {
                foreach (object obj in collection)
                {
                    ilist.Add(obj);
                }
            }
            return list;
        }
        /// <summary>
        /// 动态创建List<?> 泛型s
        /// </summary>
        /// <param name="hostType">Type类</param>
        /// <param name="table">数据源</param>
        /// <returns></returns>
        public static object DataTableToList(this Type hostType, DataTable table)
        {
            Type type = typeof(List<>).MakeGenericType(hostType);
            object list = Activator.CreateInstance(type);
            System.Collections.IList ilist = list as System.Collections.IList;

            object host = Activator.CreateInstance(hostType);
            string tempName = string.Empty;
            foreach (DataRow item in table.Rows)
            {
                PropertyInfo[] proList = hostType.GetProperties();
                foreach (PropertyInfo propertyInfo in proList)
                {
                    tempName = propertyInfo.Name;
                    if (table.Columns.Contains(tempName))
                    {
                        Object value = item[tempName];
                        if (value!=null)
                        {
                            propertyInfo.SetValue(host,value, null);
                        }
                    }
                }
                ilist.Add(host);
            }
            return list;
        }
    }
}
