检查DataRow是否包含特定列的最佳实践

问题描述:

此刻,当我遍历 DataRow 实例时,便会执行此操作。

At the moment, when I iterate over the DataRow instances, I do this.

foreach(DataRow row in table)
  return yield new Thingy { Name = row["hazaa"] };

稍后(即早一点),我会得到缺少 donkey 列,便便会引起粉丝的注意。经过大量的谷歌搜索(大约30秒)之后,我发现了以下保护语法。

Sooner of later (i.e. sooner), I'll get the table to be missing the column donkey and the poo will hit the fan. After some extensive googling (about 30 seconds) I discovered the following protection syntax.

foreach(DataRow row in table)
  if(row.Table.Columns.Contains("donkey"))
    return yield new Thingy { Name = row["hazaa"] };
  else
    return null;

现在-这是最简单的语法吗?真?我期待有一种方法可以让我获取该字段(如果存在),否则为 null 。或者至少直接在上包含一个 方法。

Now - is this the simplest syntax?! Really? I was expecting a method that gets me the field if it exists or null otherwise. Or at least a Contains method directly on the row.

我错过了什么吗?我将以这种方式在许多字段中进行映射,以使代码看起来非常不可读...

Am I missing something? I'll be mapping in many fields that way so the code will look dreadfully unreadable...

您可以创建扩展使它更整洁的方法:

You can create an extension method to make it cleaner:

static class DataRowExtensions
{
    public static object GetValue(this DataRow row, string column)
    {
        return row.Table.Columns.Contains(column) ? row[column] : null;
    }
}

现在将其命名如下:

foreach(DataRow row in table)
    return yield new Thingy { Name = row.GetValue("hazaa") };