DataTable转泛型

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;
        }
    }



你可能感兴趣的:(C#)