我有一个DataTable,它已被转换到日期列,现在看起来像这样
+--------+------------+-------------+
| | 1/1/2015 | 1/2/2015 |
+--------+-------+------------------+
| FieldA | Type | MySQL |
| FieldB | Header | Spreads |
| FieldC | Auto Align | On |
+---+------------+------------------+
我希望能够做的是根据列名和行名获取特定值。 因此,例如,如果我知道我希望FieldA的日期为2015年1月1日,我应该返回Type
用于转置DataTable的代码
public static DataTable Transpose(DataTable dt)
{
DataTable dtNew = new DataTable();
//adding columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
dtNew.Columns.Add(i.ToString());
}
//Changing Column Captions:
dtNew.Columns[0].ColumnName = " ";
for (int i = 0; i < dt.Rows.Count; i++)
{
//For dateTime columns use like below
dtNew.Columns[i + 1].ColumnName = Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");
//Else just assign the ItermArry[0] to the columnName prooperty
}
//Adding Row Data
for (int k = 1; k < dt.Columns.Count; k++)
{
DataRow r = dtNew.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
r[j] = dt.Rows[j - 1][k];
dtNew.Rows.Add(r);
}
return dtNew;
}
答案 0 :(得分:1)
您应该能够正常访问转置的DataTable
。
var monthCol = "01/01/2015"; // based on format in your code
var fieldName = "FieldA";
var res = dtTransposed.Select($"[ ] = {fieldName}")[0][monthCol]; // you really should name the first column, say "Field"
如果您知道数据的数据类型,则可以改为使用Field<>(monthCol)
。
您也可以使用LINQ:
var res = dtTransposed.AsEnumerable().Where(dr => dr[" "] == fieldName).Select(dr => dr[monthCol]);