c# - 迭代数据表时检查列是否存在?

标签 c# linq datatable contains datacolumn

我正在获取数据表并将其序列化为 geojson。我正在为此使用 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()
};

这在数据表包含所有列时有效。当列在数据表中不存在时(即 Month 列),则迭代失败。

有没有办法检查该列是否存在?我尝试使用三元运算符来检查该值,但它显然不起作用,因为我仍在检查该值是否存在。

最佳答案

您可以使用:

ReportMonth = record.Table.Columns.Contains("Month") 
            ? Convert.ToString(record["Month"])
            : string.Empty;

Convert.ToString(object) 如果对象为 null,则返回 string.Empty,因此我们不需要检查它。

这是一个速度性能优化:

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

关于c# - 迭代数据表时检查列是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58702095/

相关文章:

Odata v3 中的 C# "Resource not found for the segment"错误,状态代码为 200

c# - 使用 Roslyn 替换方法

c# - 避免 DataTable 查询和构建中的重复

c# - 使用 Entity Framework 连接多个表

c# - 使用自动增量插入

vb.net - ByVal 数据表操作

jsf-2 - 如何使用 primefaces 可选数据表迭代 HashMap

c# - 如何评论公开可见的类型枚举?

c# - 正则表达式解析 C# 源代码以查找所有字符串

c# - 如何执行连接两个实体的 LINQ 查询并在其中一个实体上选择什么位置?