/// <summary>
/// 行装换成列
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private static List<Tuple<int, string, string>> RowToCol(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
{
throw new ArgumentException("参数不能为空!");
}
int rows = 0;
List<Tuple<int, string, string>> dicList = new List<Tuple<int, string, string>>();
List<string> columns = new List<string>();
foreach (DataColumn dtCol in dt.Columns)
{
columns.Add(dtCol.ColumnName);
}
foreach (DataRow row in dt.Rows)
{
foreach (string colName in columns)
{
if (!(row[colName] is System.DBNull))
dicList.Add(new Tuple<int, string, string>(rows, colName, row[colName].ToString()));
else
dicList.Add(new Tuple<int, string, string>(rows, colName, null));
}
rows++;
}
return dicList;
}
/// <summary>
/// 列装换成行
/// </summary>
/// <param name="dicList"></param>
/// <returns></returns>
private static DataTable ColToRow(List<Tuple<int, string, string>> dicList)
{
if (dicList == null || dicList.Count == 0)
{
throw new ArgumentException("参数不能为空!");
}
int maxIndex = dicList.Max(x => x.Item1);
DataTable dataTable = new DataTable();
IEnumerable<Tuple<int, string, string>> tpFirst = dicList.Where(x => x.Item1 == 0);
foreach (Tuple<int, string, string> tp in tpFirst)
{
dataTable.Columns.Add(new DataColumn(tp.Item2));
}
for (int i = 0; i <= maxIndex; i++)
{
DataRow dataRow = dataTable.NewRow();
IEnumerable<Tuple<int, string, string>> tpList = dicList.Where(x => x.Item1 == i);
foreach (Tuple<int, string, string> tp in tpList)
{
dataRow[tp.Item2] = tp.Item3;
}
dataTable.Rows.Add(dataRow);
}
return dataTable;
}