Here's a couple of gems...
- From
IList<t></t>
to DataTable
. - From
DataTable
to array of T
.
public static DataTable ToDataTable<T>(this IList<T> iList)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection propertyDescriptorCollection =
TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < propertyDescriptorCollection.Count; i++)
{
PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
dataTable.Columns.Add(propertyDescriptor.Name,
propertyDescriptor.PropertyType);
}
object[] values = new object[propertyDescriptorCollection.Count];
foreach (T iListItem in iList)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
public static T[] ToArray<T>(this DataTable dataTable)
{
Type tType = typeof(T);
PropertyInfo[] tPropertiesInfo = tType.GetProperties();
return ToArray<T>(dataTable, tType, tPropertiesInfo,
GetColumnIndices(tPropertiesInfo,
dataTable.Columns.Cast<DataColumn>().ToArray()));
}
private static int[] GetColumnIndices(PropertyInfo[] tPropertiesInfo,
DataColumn[] dataColumns)
{
PropertyInfo tPropertyInfo;
DataColumn dataColumn;
int[] columnIndicesMappings = new int[tPropertiesInfo.Count()];
for (int i = 0; i < tPropertiesInfo.Count(); i++)
{
tPropertyInfo = tPropertiesInfo[i];
for (int j = 0; j < dataColumns.Count(); j++)
{
dataColumn = dataColumns[j];
if (tPropertyInfo.Name == dataColumn.ColumnName)
{
columnIndicesMappings[i] = j;
break;
}
}
}
return columnIndicesMappings;
}
private static T[] ToArray<T>(DataTable dataTable,
Type tType, PropertyInfo[] tPropertiesInfo, int[] columnIndices)
{
DataRow dataRow;
T tInstance;
T[] array = new T[dataTable.Rows.Count];
for (int i = 0; i < dataTable.Rows.Count; i++)
{
dataRow = dataTable.Rows[i];
tInstance = (T)Activator.CreateInstance(tType);
for (int j = 0; j < tPropertiesInfo.Count(); j++)
{
tPropertiesInfo[j].SetValue(tInstance,
dataRow[columnIndices[j]], null);
}
array[i] = tInstance;
}
return array;
}