Månad: juni 2008

ToDataTable extension for IEnumerable collections

The prolem I wanna solve is to in a very nice and shorhanded way create a System.Data.DataTable of any generic collection that inherits IEnumerable (every .NET Framework generic collection does this) building a table based on every read/write property(simple built in datatypes) that the items in the collection has. I thougt that Microsoft had build this extension already and included it in C# 3.0 but I thought wrong or maybe they included it in an early Beta version but removed it in the final release. Anyway it´s not so hard to write this extension using reflection. Here is my version of ToTableExtension.

public static class ToDataTableExtension
        public static DataTable ToDataTable<T>(this IEnumerable<T> items) where T : new()
            DataTable retVal = new DataTable();           
            T item = new T();
            Type t = item.GetType();
            retVal.TableName = "tbl" +t.Name;
            int propertyCount = t.GetProperties().Length;           
            foreach (PropertyInfo propInfo in t.GetProperties())
                if (propInfo.CanRead || propInfo.CanWrite)
                    retVal.Columns.Add(new DataColumn(propInfo.Name, propInfo.PropertyType));
            DataRow row = null;
            PropertyInfo p = null;
            foreach (T listItem in items)
                row = retVal.NewRow();
                foreach (DataColumn col in retVal.Columns)
                    p = t.GetProperty(col.ColumnName);
                    row[col.ColumnName] = p.GetValue(listItem, null);                   
            return retVal;   


Sample code that uses this Extension

List<Car> cars = new List<Car>(); cars.Add(new Car() { Weight = 1199, Speed = 0 });
DataTable table = cars.ToDataTable();
table.WriteXml(Application.StartupPath + \\cars.xml);

XML result (have nothing to do with my extension but anyway)

<?xml version="1.0" standalone="yes"?>

If you realy want to test this you also need this class

public class Car { public int Weight { get; set; } public int Speed { get; set; } }

Or download sample project here


Problem with building large solutions

The Visual Studio address space is pretty crowded, and compiling large projects takes up a lot of address space. This wouldn’t be a concern if Visual Studio spawned CSC.EXE for the build. So if you run into build scalability issues with a Visual Studio full build, you can often work around them by invoking MSBUILD.EXE from the command line supplying the .SLN file.

Some info from "A tale of two compilers" http://blogs.msdn.com/ed_maurer/archive/2008/06/11/a-tale-of-two-compilers.aspx