简体   繁体   中英

How can I check whether a dataset is empty or not in C#.net

I seen this question - how can I check whether a dataset is empty or not in C#.net - on a site for C# interview questions.

Someone answered:

DataSet ds = <get a dataset somehow>;

if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
    // There is something in the DataSet.
}

I'm some what new to C# and I am thinking there is more to this.

1.) Because he specified the zero index of the tables property, is that an assumption that there is only 1 table in the dataset? If there is only 1 table, then I understand that this will work.

2.) However, if there is more than 1 table, then am I correct to say that the above code would NOT determine if the dataset is empty?

If I am correct [#2], then would this be the way to determine whether the dataset is empty or not?

        DataSet ds = <get a dataset somehow>;

        bool dataFound = false;

        // Check to see if the dataset actually exists.
        // Check if it has one or more tables.

        if( ds != null && ds.Tables.Count > 0 )
        {
            // Check the row count for each table to see if any one table has data.
            foreach( System.Data.DataTable table in ds.Tables )
            {
                if( table.Rows.Count > 0 )
                {
                    //we have data
                    dataFound = true;
                    break;
                }
            }
        }

        if( dataFound )
        {
            Console.WriteLine( "we have data" );
        }
        else
        {
            Console.WriteLine( "we have NO data" );
        }

Regards...Dan

you can check it by this.

bool IsEmpty(DataSet dataSet)
{
    foreach(DataTable table in dataSet.Tables)
    if (table.Rows.Count != 0) return false;

    return true;
}

I hope this will work you can check it by using this

The Fill() method returns the # of rows added.

See DbDataAdapter.Fill Method (DataSet)

if(ds.Tables.Count >0)
{
    for(int i=0;i<ds.tables.count;i++)
    {
        if(ds.Tables[i].Rows.Count > )
         {
          // do your job
         }
    }
}

You are right, if there are more than one table ds.Tables[0].Rows.Count it's not valid test.

But if table exists, then dataset is not empty. If you want to check if all tables of dataset are empty, then you should traverse throw all the tables and see if any data exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM