netnr / ToDataTable.cs
2018-09-26 13:04
实体转表
/// <summary>
/// 实体转为表
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="list">对象</param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IList<T> list)
{
    Type elementType = typeof(T);
    var t = new DataTable();
    elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
    foreach (T item in list)
    {
        var row = t.NewRow();
        elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
        t.Rows.Add(row);
    }
    return t;
}
ˆ