ITeye博客

DataTable转泛型

net_liu · 2012-01-31 17:39 · C# WinForm · C# ASP.NET · 编程语言 · C# · Markdown

DataTable转泛型

 

 

public class DataHelper
    {
        /// <summary>
        /// 多个DataRow转换泛型集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="rows"></param>
        /// <returns></returns>
        public static List<T> ConvertTo<T>(List<DataRow> rows) { List<T> list = null;

            if (rows != null)
            {
                list = new List<T>();

                foreach (DataRow row in rows)
                {
                    T item = CreateItem<T>(row);
                    list.Add(item);
                }
            }

            return list;
        }

        /// <summary>
        /// Table转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public static List<T> ConvertTo<T>(DataTable table)
        {
            if (table == null)
            {
                return null;
            }

            List<DataRow> rows = new List<DataRow>();

            foreach (DataRow row in table.Rows)
            {
                rows.Add(row);
            }

            return ConvertTo<T>(rows);
        }

        public static T CreateItem<T>(DataRow row)
        {
            T obj = default(T);
            if (row != null)
            {
                obj = Activator.CreateInstance<T>();

                foreach (DataColumn column in row.Table.Columns)
                {
                    PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
                    try
                    {
                        if (prop != null && prop.CanWrite)
                        {
                            object value = row[column.ColumnName];
                            if (value != DBNull.Value)
                            {
                                prop.SetValue(obj, value, null);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // You can log something here  
                        throw;
                    }
                }
            }

            return obj;
        }
    }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。