Reputation: 1582
I've found the below "Convert to Datatable" code which I've altered to be an extension method for the IList interface. Rather than copy and paste the code again in my library I want to also make the below work for ICollection. I can copy and paste the code and change the IList at the top, then then I would have two copies of the same script.
public static DataTable ConvertToDatatable<T>(this IList<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
dataTable.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
I've even tried changing the first line to something like
public static DataTable ConvertToDatatable<T>(this N<T> data) where N : IList<T>, ICollection<T>
but having no luck. Is it possible to make the extension to work on the multiple collection types?
Upvotes: 0
Views: 91
Reputation: 22945
Since an IList<T>
is an ICollection<T>
it should be sufficient to just define the extension method on the ICollection<T>
type. It should automatically be available to a variable of type IList<T>
.
Upvotes: 1