【问题标题】:How can I validate if the column exist in a DataRow object?如何验证列是否存在于 DataRow 对象中?
【发布时间】:2013-06-19 18:20:53
【问题描述】:
private int EmploymentID { get; set; }

private void MapFields(DataRow row)
{
        if(row.HasError)
          EmploymentID = Convert.ToInt32(row["EmploymentID"].ToString());
}

代码显示它验证 DataRow 对象的行是否有错误,但我想验证它是否存在。代码有没有一种方法,而不是使用 DataRow 的 HasError 方法?

感谢您的任何友好回答。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    你也可以用这个语句

    row.Table.Columns.Contains("EmploymentID")
    

    【讨论】:

      【解决方案2】:

      DataRow 有一个 Table 属性,引用它来自的 DataTable。 DataTable 有一个 Columns 属性,它是一个DataColumnCollection。

      枚举此列表将让您确定该表是否包含您想要的列。请注意,表上的所有行都有相同的列。

      例如:

      bool containsColumn = row.Table.Columns.Any(column => column.ColumnName == "EmploymentID");
      

      值得指出的是,您可能需要检查与 DBNull 是否相等,除非您 100% 确定就业 ID 永远不会返回 null。

      此外,如果 EmploymentID 列的类型为整数,则可以通过使用直接强制转换来避免任何类型转换:

      EmploymentID = (int)row["EmploymentID"]; 
      

      或者,使用DataRowExtensions 进行更简洁的方法,它会为您执行所有空值检查:

      EmploymentID =  row.Field<int?>("EmploymentID"); 
      

      如果就业ID 不是一个可为空的 int,那么您可以像这样合并值:

      EmploymentID =  row.Field<int?>("EmploymentID") ?? 0;
      

      【讨论】:

      • 非常感谢威尔。你的回答很好。
      • @Hughes DataColumnCollection 没有任何扩展方法。至少在 .NET 4.0 中没有。
      • @Irshad - Any is in namespace System.Linq,签名public static bool Any&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate)
      • @Hughes 我知道。我补充说。但是 .Any 不适用于 DataColumnCollection。请在 VS IDE 上查看。
      • @Irshad .Any 扩展了任何 IEnumerable。 DataColumnCollection 实现 InternalDataCollectionBase,后者实现 IEnumerable。如果您有问题,您应该记录另一个问题,而不是在此处添加更多 cmets。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 2022-11-21
      • 2010-09-15
      • 2020-07-25
      • 2021-10-01
      相关资源
      最近更新 更多