Can someone help me improve this code? I and trying to have a couple extension methods to convert strongly-typed lists to a DataSet
and DataTable
respectively.
But... being so green to C#, I am not sure this is the most efficient way to do this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;
namespace o7th.Class.Library.Data
{
/// <summary>
/// List to DataTable Converter
/// </summary>
public static class ListConverter
{
/// <summary>
/// Convert our List to a DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns>DataTable</returns>
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
object[] values = new object[props.Count];
using (DataTable table = new DataTable())
{
long _pCt = props.Count;
for (int i = 0; i < _pCt; ++i)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (T item in data)
{
long _vCt = values.Length;
for (int i = 0; i < _vCt; ++i)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
}
/// <summary>
/// Convert our List to a DataSet
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns>DataSet</returns>
public static DataSet ToDataSet<T>(this IList<T> list)
{
Type elementType = typeof(T);
using (DataSet ds = new DataSet())
{
using (DataTable t = new DataTable())
{
ds.Tables.Add(t);
//add a column to table for each public property on T
PropertyInfo[] _props = elementType.GetProperties();
foreach (PropertyInfo propInfo in _props)
{
Type _pi = propInfo.PropertyType;
Type ColType = Nullable.GetUnderlyingType(_pi) ?? _pi;
t.Columns.Add(propInfo.Name, ColType);
}
//go through each property on T and add each value to the table
foreach (T item in list)
{
DataRow row = t.NewRow();
foreach (PropertyInfo propInfo in _props)
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
t.Rows.Add(row);
}
}
return ds;
}
}
}
}