2nd
April
2009
Convert List<T>/IEnumerable to DataTable/DataView
posted in Dotnet/.NET - C#, Programming |
Here’s a method to convert a generic List<T> to a DataTable. This can be used with ObjectDataSource so you get automatic sorting, etc.
/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
private DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof (T).Name);
PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}22/
return tb;
}
/// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}
-
1/22/2010 – Fix to support Nullable types.
This entry was posted
on Thursday, April 2nd, 2009 at 7:00 pm and is filed under Dotnet/.NET - C#, Programming.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
posted on April 5th, 2009 at 9:27 pm
posted on July 3rd, 2009 at 6:52 am
posted on August 7th, 2009 at 2:29 am
posted on November 10th, 2009 at 5:47 pm
posted on December 2nd, 2009 at 5:09 pm
posted on December 2nd, 2009 at 5:32 pm
posted on December 11th, 2009 at 11:25 am
posted on December 16th, 2009 at 1:26 am
posted on January 22nd, 2010 at 8:36 am
posted on January 22nd, 2010 at 8:50 am
posted on June 24th, 2010 at 10:22 am
posted on June 24th, 2010 at 10:39 pm
posted on February 8th, 2011 at 4:36 pm
posted on February 8th, 2011 at 5:01 pm
posted on March 4th, 2011 at 5:24 am
posted on March 15th, 2011 at 6:40 pm
posted on April 7th, 2011 at 9:32 am
posted on September 27th, 2011 at 7:58 am