I'm working with a dataset that is already populated. I am iterating over the rows in a table like so:
foreach (DataRow row in this.dataSet.Tables["tablename"].Rows)
{
// do something
}
this works fine, unless there are no rows, in which case there is no table, so I get an 'object not set to an instance of an object' style error. (i.e. this.dataSet.Tables["tablename"] is null so I'm in effect calling null.Rows, which of course borks).
To get around this I'm doing:
if (this.dataSet.Tables.Contains("tablename"))
{
foreach (DataRow row in this.dataSet.Tables["tablename"].Rows)
{
// do something
}
}
which is, frankly, ugly as sin. I'm guessing this is because .net returns null not a null object.
Is there a way that I can simply loop over a table's rows, that if the table doesn't exist loops over an empty collection?
No you can't. Best thing you can do is hide the checking in an extension method.
If table exist, return the table rows, otherwise return empty sequence.
public static class DataSetExtensions
{
public static IEnumerable<DataRow> RowsOfTable(this DataSet dataSet, string tableName)
{
if (dataSet.Tables.Contains(tableName))
return dataSet.Tables[tableName].AsEnumerable();
return Enumerable.Empty<DataRow>();
}
}
Then use it as
DataSet dataSet = new DataSet();
foreach (DataRow row in dataSet.RowsOfTable("tablename"))
{
// do something
}