简体   繁体   中英

Check if column exists when iterating datatable?

I'm taking a datatable and serializing it as geojson. I'm using linq for this:

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.

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.

For validation, you could wrap in a try ... catch and rethrow with your own custom error.

For null coallesce, something like:

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.

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(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM