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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18208311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:32:29  来源:igfitidea点击:

Best practice to check if DataRow contains a certain column

c#dataset

提问by Konrad Viltersten

At the moment, when I iterate over the DataRowinstances, I do this.

目前,当我遍历DataRow实例时,我会这样做。

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

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

的迟早(即更快),我会得到失踪列和便便将达到风扇。经过一些广泛的谷歌搜索(大约 30 秒),我发现了以下保护语法。

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

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

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

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

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

采纳答案by Varun K

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;
    }
}

Now call it like below:

现在像下面这样调用它:

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

回答by Heslacher

As your DataTable table always has the same columns ( they won`t change for any row ) you only need to check for the columnname once.

由于您的 DataTable 表始终具有相同的列(它们不会为任何行更改),您只需要检查一次列名。

if (table.Columns.Contains("donkey"))
{
    foreach ...
}

回答by Driton

foreach (DataColumn item in row.Table.Columns)
{
    switch (item.ColumnName)
    {
        case "ID":
            {
                p.ID = Convert.ToInt32(row[item.ColumnName].ToString());
            }
            break;
        case "firstName":
            {
                p.firstName = row[item.ColumnName].ToString();
            }
            break;
        case "lastName":
            {
                p.lastName = row[item.ColumnName].ToString();
            }
            break;

        default:
            break;
    };
}

回答by howcheng

To build on the answer by Varun K, use a generic type parameter:

要以 Varun K 的答案为基础,请使用泛型类型参数:

public static T GetValue<T>(this DataRow row, string column)
{
    if (!row.Table.Columns.Contains(column))
        return default(T);

    object value = row[ColumnName];
    if (value == DBNull.Value)
        return default(T);
    return (T)value;
}