数据库的查询结果通常为每一行为单独的信息,有时需要以某一列为基准(姓名),将某一列(科目)转换成行
///
///
///
///
数据源
///
主键列
///
转换列
///
数值列
///
///
public DataTable GetCrossTable(DataTable sourceTable, int indexColumn, int crossColumn, int valueColumn, string sortStr, string defaultValue)
{
if (sourceTable == null || sourceTable.Rows.Count == 0)
{
return sourceTable;
}
else
{
DataTable resultTable = GetCrossColumns(sourceTable, crossColumn, valueColumn, defaultValue);
string indexName = sourceTable.Columns[indexColumn].ColumnName;
SetCrossValue(resultTable, sourceTable, indexColumn, crossColumn, valueColumn);
DataView dv = resultTable.DefaultView;
dv.Sort = indexName + " " + sortStr;
return dv.ToTable();
}
}
private DataTable GetCrossColumns(DataTable sourceTable, int crossColumn, int valueColumn, string defaultValue)
{
DataTable result = new DataTable();
#region 添加原列
for (int i = 0; i < sourceTable.Columns.Count; i++)
{
if (i != crossColumn && i != valueColumn)
{
result.Columns.Add(sourceTable.Columns[i].ColumnName);
}
}
#endregion
#region 添加转换后列
DataTable dtColumns = sourceTable.DefaultView.ToTable("dtColumns", true, sourceTable.Columns[crossColumn].ColumnName);
for (int i = 0; i < dtColumns.Rows.Count; i++)
{
string colName;
if (dtColumns.Rows[i][0] is DateTime)
{
colName = Convert.ToDateTime(dtColumns.Rows[i][0]).ToString();
}
else
{
colName = dtColumns.Rows[i][0].ToString();
}
result.Columns.Add(colName);
result.Columns[result.Columns.Count - 1].DefaultValue = defaultValue;
}
#endregion
return result;
}
private void SetCrossValue(DataTable resultTable, DataTable sourceTable, int indexColumn, int crossColumn, int valueColumn)
{
#region 赋值
string indexName = sourceTable.Columns[indexColumn].ColumnName;
DataRow drNew = resultTable.NewRow();
bool isNew = true;
for (int i = 0; i < sourceTable.Columns.Count - 2; i++)
{
drNew[i] = sourceTable.Rows[0][resultTable.Columns[i].ColumnName];
}
string rowName = drNew[indexName].ToString();
foreach (DataRow dr in sourceTable.Rows)
{
bool isExist = false;
string colName = dr[crossColumn].ToString();
double dValue = Convert.ToDouble(dr[valueColumn]);
if (dr[indexColumn].ToString().Equals(rowName, StringComparison.CurrentCultureIgnoreCase))
{
drNew[colName] = dValue.ToString();
}
else
{
for (int i = 0; i < resultTable.Rows.Count; i++)
{
if (dr[indexColumn].ToString() == resultTable.Rows[i][indexName].ToString())
{
if (isNew)
{
resultTable.Rows.Add(drNew);
}
isExist = true;
isNew = false;
drNew = resultTable.Rows[i];
drNew[colName] = dValue.ToString();
rowName = drNew[indexName].ToString();
break;
}
}
if (!isExist)
{
if (isNew)
{
resultTable.Rows.Add(drNew);
}
isNew = true;
drNew = resultTable.NewRow();
for (int i = 0; i < sourceTable.Columns.Count - 2; i++)
{
drNew[i] = dr[resultTable.Columns[i].ColumnName];
}
rowName = drNew[indexName].ToString();
drNew[colName] = dValue.ToString();
}
}
}
if (isNew)
{
resultTable.Rows.Add(drNew);
}
#endregion
}