Search code examples
c#linqdatatablecontainsdatacolumn

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.


Solution

  • 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 ? ... : ... ;
    }