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

Best practice to check if DataRow contains a certain column(检查 DataRow 是否包含特定列的最佳实践)
本文介绍了检查 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 是否包含特定列的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)