c# DataTable 帮助类

人生乱弹 1年前 (2024) admin
7 0

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
    }

文章来源

版权声明:admin 发表于 2024年2月11日 am4:35。
转载请注明:c# DataTable 帮助类 | 银库

相关文章

本站主题由 OneNav 一为主题强力驱动