Thursday, July 1, 2010

Convert List/IEnumerable to DataTable/DataView

Here’s a method to convert a generic List to a DataTable. This can be used with ObjectDataSource so you get automatic sorting, etc.
01///
02/// Convert a List{T} to a DataTable.
03///
04private DataTable ToDataTable(List items)
05{
06    var tb = new DataTable(typeof (T).Name);
07 
08    PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
09 
10    foreach (PropertyInfo prop in props)
11    {
12        Type t = GetCoreType(prop.PropertyType);
13        tb.Columns.Add(prop.Name, t);
14    }
15 
16    foreach (T item in items)
17    {
18        var values = new object[props.Length];
19 
20        for (int i = 0; i < props.Length; i++)
21        {
22            values[i] = props[i].GetValue(item, null);
23        }
24 
25        tb.Rows.Add(values);
26    }22/
27 
28    return tb;
29}
30 
31///
32/// Determine of specified type is nullable
33///
34public static bool IsNullable(Type t)
35{
36    return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
37}
38 
39///
40/// Return underlying type if type is Nullable otherwise return the type
41///
42public static Type GetCoreType(Type t)
43{
44    if (t != null && IsNullable(t))
45    {
46        if (!t.IsValueType)
47        {
48            return t;
49        }
50        else
51        {
52            return Nullable.GetUnderlyingType(t);
53        }
54    }
55    else
56    {
57        return t;
58    }
59}

No comments: