我正在将文件中的值导入到数据表中,其中一列是位置列,不幸的是它同时包含纬度和经度值,这需要我将它们拆分。
理想情况下,我想要两个计算值,纬度和经度,但是我不知道如何编写 DataColumn.Expression 属性的表达式。
private void CalcColumns()
{
DataTable table = new DataTable ();
// Create the first column.
DataColumn locationColumn = new DataColumn();
locationColumn.ColumnName = "Location (Lat, Long)";
locationColumn.DefaultValue = "40.00, -60.00";
// Create the second, calculated, column.
DataColumn latColumn = new DataColumn();
latColumn.ColumnName = "Latitude";
latColumn.Expression = ""; // what expression goes here
// Create third column.
DataColumn longColumn = new DataColumn();
longColumn.ColumnName = "Longitude";
longColumn.Expression = ""; // what expression goes here
// Add columns to DataTable.
table.Columns.Add(locationColumn);
table.Columns.Add(latColumn);
table.Columns.Add(longColumn);
DataRow row = table.NewRow();
table.Rows.Add(row);
DataView view = new DataView(table);
dataGrid1.DataSource = view;
}
我尝试了 Expression = "SUBSTRING(Location (Lat, Long),1,5)" 但这给了我一个错误:
System.Data.EvaluateException: 'The expression contains undefined function call Location().'
所以,尝试了 Expression = "SUBSTRING('Location (Lat, Long)',1,5)" 但这给了我
Locat
。
https://learn.microsoft.com/en-us/dotnet/api/system.data.datacolumn.expression?view=net-8.0 Microsoft 文档中的示例显示:
private void CalcColumns()
{
DataTable table = new DataTable ();
// Create the first column.
DataColumn priceColumn = new DataColumn();
priceColumn.DataType = System.Type.GetType("System.Decimal");
priceColumn.ColumnName = "price";
priceColumn.DefaultValue = 50;
// Create the second, calculated, column.
DataColumn taxColumn = new DataColumn();
taxColumn.DataType = System.Type.GetType("System.Decimal");
taxColumn.ColumnName = "tax";
taxColumn.Expression = "price * 0.0862";
// Create third column.
DataColumn totalColumn = new DataColumn();
totalColumn.DataType = System.Type.GetType("System.Decimal");
totalColumn.ColumnName = "total";
totalColumn.Expression = "price + tax";
// Add columns to DataTable.
table.Columns.Add(priceColumn);
table.Columns.Add(taxColumn);
table.Columns.Add(totalColumn);
DataRow row = table.NewRow();
table.Rows.Add(row);
DataView view = new DataView(table);
dataGrid1.DataSource = view;
}
所以,我应该能够将列名称引用为:位置(纬度,经度),但这引发了错误。
如何编写表达式来获取我想要的值?
因为括号的原因,需要转义字符。 IRC `` 或 [] 可以工作(可能取决于 .NET 版本),所以你需要:
"SUBSTRING([Location (Lat, Long)],1,5)"
或
"SUBSTRING(`Location (Lat, Long)`,1,5)"
如果您对该列有更多引用,可以在脚本过程中考虑使用更 C# 友好的名称(例如 LocationLatLong),然后修复最终输出。