2

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.

fdkgfosfskjdlsjdlkfsf
  • 3,165
  • 2
  • 43
  • 110

2 Answers2

1

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 ? ... : ... ;
}
  • This will iterate the datatable multiple times, not a good solution inside linq statement. Why not use the datarow object you have? Also an explanation of the actual issue the OP is having would be nice as well. – Trevor Nov 04 '19 at 23:07
  • And for every record in that table your doing a lookup, hence why i said its not a good solution. You don't need to lookup everytime, only one time is needed. – Trevor Nov 04 '19 at 23:16
  • Indeed, we can check before the query to initialize some booleans if afraid of speed performance. –  Nov 04 '19 at 23:18
0

You could try record.Table.Columns.Contains(...).

tymtam
  • 31,798
  • 8
  • 86
  • 126