[英]Manipulating Column in DataTable C#
我正在C#中使用DataTable
,並試圖操縱,修改列之一。 考慮以下示例數據
Id City Temperature
-------------------
1 A -12
2 B 23
3 C 12
轉換后,我想要下面的結果,將負號轉換為M,將正值轉換為P
Id City Temperature
-------------------------
1 A 12M
2 B 23P
3 C 12P
我可以使用LINQ..Am解析約50k行來實現這一點,並且不希望在性能上有所妥協。其他最佳方法是什么?
如果列是string
而不是double
/ int
:
foreach(DataRow row in table.Rows)
{
string temp = row.Field<string>("Temperature");
bool negative = temp.StartsWith("-");
temp = negative ? temp.Substring(1) + "M" : temp + "P";
row.SetField("Temperature", temp);
}
如果列類型為double
如現在所述,則必須創建一個新的DataTable
。 你不能改變的DataType
后Datatable
填充數據。
DataTable newTable = table.Clone();
int ordinal = newTable.Columns.IndexOf("Temperature");;
newTable.Columns.Remove("Temperature"); // remove double-column
DataColumn tempCol = newTable.Columns.Add("Temperature"); // string
tempCol.SetOrdinal(ordinal);
foreach (DataRow row in table.Rows)
{
DataRow newRow = newTable.Rows.Add();
foreach(DataColumn col in newTable.Columns)
{
if (col == tempCol)
{
double temp = row.Field<double>("Temperature");
bool negative = temp < 0;
double abs = Math.Abs(temp);
string newTemp = negative ? abs.ToString() + "M" : abs.ToString() + "P";
newRow.SetField(col, newTemp);
}
else
newRow.SetField(col, row[col.ColumnName]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.