0
点赞
收藏
分享

微信扫一扫

os模块

脱下愤怒的小裤衩 2024-02-10 阅读 11

public class DataTableHelper
    {
        #region DataTable转IList

        /// <summary>
        /// DataTable转IList集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static IList<T> ToList<T>(DataTable dataTable) where T : class, new()
        {
            IList<T> list = new List<T>();// 定义集合
            if (dataTable != null)
            {
                foreach (DataRow dr in dataTable.Rows)
                {
                    T t = new T();
                    PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                    foreach (PropertyInfo pi in propertys)
                    {
                        var name = pi.Name;
                        if (dataTable.Columns.Contains(name))
                        {
                            if (!pi.CanWrite) continue;
                            object value = dr[name];
                            if (value != DBNull.Value)
                            {
                                pi.SetValue(t, value, null);
                            }
                        }
                    }
                    list.Add(t);
                }
            }
            return list;
        }
        #endregion
    }

举报

相关推荐

0 条评论