I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?
I would suggest something like:-
bool nonEmptyDataSet = dataSet != null &&
(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
Edits: I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of .Any().
In line with Keith's suggestion, here is an extension method version of this approach:-
public static class ExtensionMethods {
public static bool IsEmpty(this DataSet dataSet) {
return dataSet == null ||
!(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
}
}
Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null.
What's wrong with
(aDataSet.Tables.Count == 0)
?
I have created a small static util class just for that purpose
Below code should read like an English sentence.
public static bool DataSetIsEmpty(DataSet ds)
{
return !DataTableExists(ds) && !DataRowExists(ds.Tables[0].Rows);
}
public static bool DataTableExists(DataSet ds)
{
return ds.Tables != null && ds.Tables.Count > 0;
}
public static bool DataRowExists(DataRowCollection rows)
{
return rows != null && rows.Count > 0;
}
I would just put something like below code and be done with it. Writing a readable code does count.
if (DataAccessUtil.DataSetIsEmpty(ds)) {
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With