检查DataRow是否包含特定列的最佳实践 [英] Best practice to check if DataRow contains a certain column

查看:68
本文介绍了检查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") };

这篇关于检查DataRow是否包含特定列的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆