Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to check if DataRow contains a certain column

Tags:

c#

dataset

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

like image 432
Konrad Viltersten Avatar asked Aug 13 '13 11:08

Konrad Viltersten


People also ask

How do I check if a DataRow column exists?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

How do you check if a column exists in a DataRow vb net?

You can use DataSet. Tables(0). Columns. Contains(name) to check whether the DataTable contains a column with a particular name.

How do I find my DataRow column name?

You can get the column names from DataRow by using (datarow). Table. Columns and this will return “DataColumnCollection”.


1 Answers

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") }; 
like image 75
Varun K Avatar answered Sep 20 '22 10:09

Varun K