ToView
Extend collections implementing IList to return a DataView. In cases where filters need to be applied to data, this extension will prove handy.
Source
/// <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); ;
}
Example
public class TestEntity
{
public int ID { get; private set; }
public string Name { get; set; }
public TestEntity(int ID, string Name)
{
this.ID = ID;
this.Name = Name;
}
public static List<TestEntity> GetTestData()
{
List<TestEntity> test = new List<TestEntity>();
test.Add(new TestEntity(1, "Test 1"));
test.Add(new TestEntity(2, "Test 2"));
test.Add(new TestEntity(3, "Test 3"));
test.Add(new TestEntity(4, "Test 4"));
return test;
}
public static System.Data.DataView GetView(List<TestEntity> list)
{
return list.ToView();
}
}
Author: Felipe Ramos
Submitted on: 23 feb. 2011
Language: C#
Type: System.Collections.IList
Views: 5110