您的位置:首页 > 其它

其他类型转化成DataTable

2017-11-08 14:17 218 查看
class Program
{
static void Main(string[] args)
{
List<Student> list = new List<Student>();
list.Add(new Student()
{
ID = 1,
Name = "Fabre",
Sex = true,
Age = 27,
Birthday = DateTime.Now
});
string[] strTitle = new string[] { "ID", "Name", "Sex", "Age", "Birthday" };
DataTable dt = GetDataTable(list, strTitle);
}

public static  DataTable GetDataTable(dynamic objects, string[] strFields)
{
DataTable dt = new DataTable();
bool isFirst = true;
foreach (var obj in objects)
{
DataRow dr = dt.NewRow();
foreach (string item in strFields)
{
if (isFirst)
{
dt.Columns.Add(item);//创建列
}
dr[item] = GetPropertyValue(obj, item);//单元格赋值
}
isFirst = false;//第一次创建表头,往后都不用创建了,用一个标识处理
dt.Rows.Add(dr);
}
return dt;
}

/// <summary>
/// 获取一个实例指定的属性值
/// </summary>
/// <param name="info">object对象</param>
/// <param name="field">属性名称</param>
/// <returns></returns>
public static object GetPropertyValue(object info, string field)
{
if (info == null)
{
return null;
}
Type t = info.GetType();
IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties()
where pi.Name.ToLower() == field.ToLower()
select pi;
if (property.Count() < 1)
{
return "";
}
return property.First().GetValue(info, null);
}
}

public class Student
{
public int ID { get; set; }
public string Name { get; set; }
//true 男 false 女
public bool Sex { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: