[英]Check if column exists when iterating datatable?
I'm taking a datatable and serializing it as geojson.我正在获取一个数据表并将其序列化为 geojson。 I'm using linq for this:
我为此使用 linq :
var envelope = new
{
type = "FeatureCollection",
features = dataTable.AsEnumerable().Select(record => new {
type = "Feature",
properties = new
{
Name = Convert.ToString(record["Name"]),
Date = Convert.ToString(record["Date"]),
Icon = Convert.ToString(record["imageUrl"]),
//ReportMonth = Convert.ToString(record["Month"]),
ReportMonth = (!string.IsNullOrEmpty(record["Month"])) ? Convert.ToString(record["ReportMonth"]) : string.Empty
},
geometry = new
{
type = "Point",
coordinates = new[] {
Convert.ToDecimal(record["Lon"]),
Convert.ToDecimal(record["Lat"])
}
}
}).ToArray()
};
This works when the datatable has all the columns.当数据表包含所有列时,此方法有效。 When the column doesn't exist in the datatable (ie. column
Month
) then the iteration fails.当数据表中不存在该列时(即列
Month
),则迭代失败。
Is there a way to check if the column exists?有没有办法检查列是否存在? I tried using a ternary operator to check the value, but it obviously won't work since I'm still checking if the value exists.
我尝试使用三元运算符来检查该值,但显然它不起作用,因为我仍在检查该值是否存在。
What do you want to do if the column does / does not exist?如果列不存在/不存在,你想做什么? Throw an error?
抛出错误? If so, you should validate before you read.
如果是这样,您应该在阅读之前进行验证。 Assign a default value?
分配默认值? Null coallesce.
Null 合并。
For validation, you could wrap in a try
... catch
and rethrow with your own custom error.对于验证,您可以使用您自己的自定义错误包裹在
try
... catch
和 rethrow 中。
For null coallesce, something like:对于 null 合并,类似于:
ReportMonth = Convert.ToString(record["ReportMonth"]?? string.Empty)
You can use:您可以使用:
ReportMonth = record.Table.Columns.Contains("Month")
? Convert.ToString(record["Month"])
: string.Empty;
Convert.ToString(object)
returns string.Empty
if the object is null
so we don't need to check it.如果 object 是
null
, Convert.ToString(object)
返回string.Empty
,所以我们不需要检查它。
Here is a speed performance optimization:下面是速度性能优化:
bool hasName = dataTable.Columns.Contains("Name");
bool hasDate = dataTable.Columns.Contains("Date");
bool hasimageUrl = dataTable.Columns.Contains("imageUrl");
bool hasMonth = dataTable.Columns.Contains("Month");
bool hasLon = dataTable.Columns.Contains("Lon");
bool hasLat = dataTable.Columns.Contains("Lat");
var envelope = new
{
// use: ReportMonth = hasMonth ? ... : ... ;
}
You could try record.Table.Columns.Contains(...)
.您可以尝试
record.Table.Columns.Contains(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.