Possible Duplicate:
Convert IEnumerable to DataTable
I just want to Convert a List or IEnumerable to DataTable, through a extension method or Util class.
Possible Duplicate:
Convert IEnumerable to DataTable
I just want to Convert a List or IEnumerable to DataTable, through a extension method or Util class.
I use the following extension method to generate a Database from IEnumerable. Hopefully this helps.
        public static DataTable ToDataTable<TSource>(this IEnumerable<TSource> source)
        {
            var tb = new DataTable(typeof (TSource).Name);
            var props = typeof (TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }
            foreach (var item in source)
            {
                var values = new object[props.Length];
                for (var i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }
                tb.Rows.Add(values);
            }
            return tb;
        }
    public static Type GetCoreType(Type t)
    {
        return t != null && IsNullable(t) 
               ? (!t.IsValueType ? t : Nullable.GetUnderlyingType(t)) : t;
    }
    public static bool IsNullable(Type t)
    {
        return !t.IsValueType || (t.IsGenericType 
               && t.GetGenericTypeDefinition() == typeof(Nullable<>));
    }