Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to check dataset has records

Tags:

c#

dataset

I am keen to know the best approach to check if a dataset has records in it or not. I have been using the below code to check if a dataset has some records or not. But I feels there is some better/best approach available to achieve this.

Dataset tableData = New Dataset();
if (_tableData.Tables.Count > 0 && _tableData.Tables[0].Rows.Count > 0)
{ 
}

Please share some knowledge if I am feeling correct.

Thanks

like image 994
Deepak Kumar Avatar asked Nov 23 '25 23:11

Deepak Kumar


2 Answers

This will return true if there are any rows in any of the tables. It will return false if there are no tables or no rows.

DataSet tableData; // ... instantiate DataSet
bool hasRows = tableData.Tables.Cast<DataTable>()
                               .Any(table => table.Rows.Count != 0);
like image 120
Roy Goode Avatar answered Nov 25 '25 11:11

Roy Goode


If there are multiple tables in your DataSet then your logic won't work for some scenarios. This method is more complete:

bool HasRecords(DataSet dataSet)
{
    foreach (DataTable dt in dataSet.Tables) if (dt.Rows.Count > 0) return true;
    return false;
}
like image 26
Tomek Avatar answered Nov 25 '25 13:11

Tomek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!