首页 技术 正文
技术 2022年11月20日
0 收藏 332 点赞 2,459 浏览 1746 个字

public static class ExtensionMethods
{
/// <summary>
/// 将List转换成DataTable
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <param name=”data”></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dt = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dt.Columns.Add(property.Name, property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dt.Rows.Add(values);
}
return dt;
}

/// <summary>
/// DataTable转泛型
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <param name=”dt”>DataTable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
//获取类
Type t = typeof(T);
//反射 using System.Reflection;
//获取当前Type的公共属性
PropertyInfo[] propertys = t.GetProperties();
List<T> list = new List<T>();
//字段名称
string typeName = string.Empty;
//遍历DataTable每行
foreach (DataRow dr in dt.Rows)
{
//创建实体
T entity = new T();
//遍历实体的公共属性
foreach (PropertyInfo pi in propertys)
{
//将字段名称赋值
typeName = pi.Name;
if (dt.Columns.Contains(typeName))
{
//获取一个值,该值指定此属性是否可写 set 
if (!pi.CanWrite) continue;
//根据字段名称获取对应值
object value = dr[typeName];
//若不存在 则跳出
if (value == DBNull.Value) continue;
//获取此属性的类型是否是string类型
if (pi.PropertyType == typeof(string))
{
//PropertyInfo.SetValue()三个参数
//第一个 将设置其属性值的对象。
//第二个 新的属性值。
//第三个 索引化属性的可选索引值。 对于非索引化属性,该值应为 null。
pi.SetValue(entity, value.ToString(), null);
}
else if (pi.PropertyType == typeof(int))
{
//写入
pi.SetValue(entity, int.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(DateTime))
{
//写入
pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
}
else
{
pi.SetValue(entity, value, null);
}
}
}
//加入泛型末尾
list.Add(entity);
}
return list;
}
}

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,074
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,551
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,399
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,811
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,892