///
<summary>|
///
Extend any collection implementing IList to return a DataView.
///
</summary>
///
<param name="list">IList
(Could be List<Type>)</param>
///
<returns>DataView</returns>
public
static
DataView ToView(this
IList list)
{
// Validate Source
if (list.Count <
1)
return
null;
// Initialize DataTable and get
all properties from the first Item in the List.
DataTable table =
new
DataTable(list.GetType().Name);
PropertyInfo[] properties
= list[0].GetType().GetProperties();
// Build all columns from
properties found. (Custom attributes could be added later)
foreach (PropertyInfo
info in properties)
{
try
{
table.Columns.Add(new
DataColumn(info.Name,
info.PropertyType));
}
catch (NotSupportedException)
{
// DataTable does not
support Nullable types, we want to keep
underlying type.
table.Columns.Add(new
DataColumn(info.Name,
Nullable.GetUnderlyingType(info.PropertyType)));
}
catch (Exception)
{
table.Columns.Add(new
DataColumn(info.Name,
typeof(object)));
}
}
// Add all rows
for (int
index = 0; index < list.Count; index++)
{
object[] row =
new object[properties.Length];
for (int
i = 0; i < row.Length; i++)
{
row[i] = properties[i].GetValue(list[index],
null); // Get
the value for each items property
}
table.Rows.Add(row);
}
return
new DataView(table);
;
} |