//自己写一个List 行转列 返回table的方法
public DataTable RowToColByList<T>(List<T> list,string colName)
{
DataTable dt = new DataTable();
var properties = new List<PropertyInfo>(typeof(T).GetProperties());
// Col1 Col2 Col3 Col4 Col5 Col6
// A A AB AD C 1
// B A AB A A 2
// C C C B AD 3
// Col6的值变为列名,多加了一列(name)显示原先的列名当做行,
// name 1 2 3
// Col1 A B C
// Col2 A A C
// Col3 AB AB C
// Col4 AD A A
// Col5 C A D
//第一步,先把colName对应的一列数据添加为dt的列,该列不能用重复数据,在数据库做处理
dt.Columns.Add("name");
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < properties.Count; j++)
{
if (string.Equals(colName, properties[j].Name))
{
dt.Columns.Add(properties[j].GetValue(list[i]).ToString());
}
}
}
//第二步。插入数据
for (int j = 0; j < properties.Count; j++)
{
DataRow dr = dt.NewRow();
dr[0]= properties[j].Name;
for (int i = 0; i < list.Count; i++)
{
dr[i + 1] = list[i].GetType().GetProperty(properties[j].Name).GetValue(list[i]);
}
dt.Rows.Add(dr);
}
return dt;
}