Just a quick post about a very handy method I found on Stack Overflow. This lets you transform a list of C# objects into a data table. This can be very handy for debugging purposes, if nothing else. Being able to quickly see a large list of objects and all of their properties in one nice condensed view. Credit to Harshil Raval at http://stackoverflow.com/questions/18100783/how-to-convert-a-list-into-data-table
private DataTable ToDataTable<T>(List<T> 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); } 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; }
Leave A Comment