Monday, January 17, 2005

Empty Dataset?

Nick hodges has a post on when is a dataset truly empty in .Net. The code he has in Delphi for .Net goes as follows:

function DatasetIsEmpty(const aDataset: Dataset): Boolean;
var
 TempTable: DataTable;
begin
 Result := (aDataset = nil) or (aDataset.Tables.Count = 0);
  if Result then
  begin
   for TempTable in aDataset.Tables do
   begin
    Result := Result and (TempTable.Rows.Count = 0);
   end;
  end;
end;

Unfortunately it looks to me the if statement has the logic incorrect (thus my placing it in red). Result will be true if aDataset is nil (or null for you non-Delphi types). Running this with a nil dataset will result in:

Encountered unhandled exception class System.NullReferenceException with message 'Object reference not set to an instance of an object.'.

Change it to if not Result then and I you will be good. If you want it to be more efficient on datasets with a lot of tables then you might change it like this:

function DatasetIsEmpty(const aDataset: Dataset): Boolean;
var
TempTable: DataTable;
begin
Result := (aDataset = nil) or (aDataset.Tables.Count = 0);
  if not Result then
  begin
  for TempTable in aDataset.Tables do
  begin
    Result := (TempTable.Rows.Count = 0);
    if not Result then
    begin
      break;
    end;
  end;
  end;
end;

This way if ever find a populated table it stops immediately.

Don't do Delphi? Here is a version of the code for C#

public bool DatasetIsEmpty ( System.Data.DataSet aDataset )
{
 bool Result = ( aDataset == null ) || ( aDataset.Tables.Count == 0 );

 if ( !Result )
 {
   foreach ( DataTable TempTable in aDataset.Tables )
   {
     Result = ( TempTable.Rows.Count == 0 );
     if ( !Result )
     {
       break;
     }
   }
 }

 return ( Result );
}

1 comment:

unused said...

It is Jim, not Nick. Nick is at www.lemanix.com/nick/ . Sure, that is more readable. Just trying not to change Nick's original code too much.