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

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

迟早(即早),我会让 table 缺少列 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 否则.或者至少在 row 上直接有一个 Contains 方法.

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...

推荐答案

我真的很喜欢@Varun K 采用的方法.因此,以此为出发点,我只想投入两分钱,以防它对某人有所帮助别的.我只是对其进行了改进,使其成为 generic 而不仅仅是使用 object 作为返回类型.

I really liked the approach taken by @Varun K. So, having that as a departing point I just wanted to put my two cents, in case it helps someone else. I simply improved it making it generic instead of just using object as a return type.

static class Extensions
{
  public static T Get<T>(this DataRow self, string column)
  {
    return self.Table.Columns.Contains(column)
      ? (T)self[column]
      : default(T);
    }
  }
}

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

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