Monday, January 30, 2012

Best Extension Methods: Convert IEnumerable To DataTable

This extension method converts IEnumerable to DataTable

 public static DataTable ToDataTable(this IEnumerable items)
    {
        var tb = new DataTable(typeof(T).Name);
        PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var prop in props)
        {
            //tb.Columns.Add(prop.Name, prop.PropertyType);
            Type t = GetCoreType(prop.PropertyType);
            tb.Columns.Add(prop.Name, t);
        }

        foreach (var item in items)
        {
            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;
    }

Compiled By: Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates