AnonymousType to DataTable madness!

by Kev Ritchie 5. November 2010 21:53

Today I was working on converting a project over to WPF.  Everything was going well until I needed to put the results of a LINQ query into a DataTable.

There didn't seem to be any easy way to do it, unless I'm being really blind Laughing.  Well, after some research and tinkering, I chucked together this little handy method:

private DataTable QueryResults<T>(IEnumerable<T> anon)
{
    DataTable results = new DataTable();
 
    if (anon != null)
    {
        PropertyInfo[] columns = null;
 
        foreach (T item in anon)
        {
            if (columns == null)
            {
                columns = ((Type)item.GetType()).GetProperties();
 
                foreach (PropertyInfo column in columns)
                {
                    Type columnType = column.PropertyType;
 
                    if ((columnType.IsGenericType) && (columnType.GetGenericTypeDefinition()
                        == typeof(Nullable<>)))
                    {
                        columnType = columnType.GetGenericArguments()[0];
                    }
 
                    results.Columns.Add(new DataColumn(column.Name, columnType));
                }
            }
 
            DataRow dr = results.NewRow();
 
            foreach (PropertyInfo column in columns)
            {
                dr[column.Name] = column.GetValue(item, null) == null ?
                    DBNull.Value : column.GetValue(item, null);
            }
 
            results.Rows.Add(dr);
 
        }
    }
 
    return results;
}
You can also pass in objects of type ISingleResult e.g Stored Procedures, into this method.

Have a go and let me know what you think

Powered by BlogEngine.NET 2.5.0.6
Theme by Mads Kristensen | Modified by Mooglegiant