Best practice to check if DataRow contains a certa

2020-02-08 05:02发布

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

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;

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

标签: c# dataset
4条回答
Fickle 薄情
2楼-- · 2020-02-08 05:19

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.

if (table.Columns.Contains("donkey"))
{
    foreach ...
}
查看更多
够拽才男人
3楼-- · 2020-02-08 05:20
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;
    };
}
查看更多
男人必须洒脱
4楼-- · 2020-02-08 05:20

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

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;
}
查看更多
Fickle 薄情
5楼-- · 2020-02-08 05:27

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") };
查看更多
登录 后发表回答