2

Possible Duplicate:
Convert IEnumerable to DataTable

I just want to Convert a List or IEnumerable to DataTable, through a extension method or Util class.

Community
  • 1
  • 1
  • 1
    can you be more precise? do you want to create a new datatable, containing a snapshot of the properties/fields of your instances of T, or do you want some sort of proxy object that represents your instances of T through a datatable-like shape? – DarkSquirrel42 Jul 08 '11 at 00:21
  • 1
    Why do you want to do this exactly? There could be a better way. – Ry- Jul 08 '11 at 00:23

1 Answers1

0

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<>));
    }
Nickz
  • 1,880
  • 17
  • 35