Best practice to check if DataRow contains a certain column

后端 未结 5 1997
无人及你
无人及你 2020-12-13 17:28

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\"]         


        
相关标签:
5条回答
  • 2020-12-13 17:39

    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;
    }
    
    0 讨论(0)
  • 2020-12-13 17:47

    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") };
    
    0 讨论(0)
  • 2020-12-13 17:51

    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 ...
    }
    
    0 讨论(0)
  • 2020-12-13 17:55
    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;
        };
    }
    
    0 讨论(0)
  • 2020-12-13 17:56

    Sometimes a column name might exist, but a row does not contain the data for that column; for example, after filling DataTable using ReadXML.

    A simple, fast and secure solution would be to use type checking:

    if(row["columnname"].GetType() != typeof(System.DBNull)){
        //DataRow contains "columname"
    }else{
        //a safe scope to set default cell data
    }
    
    0 讨论(0)
提交回复
热议问题