简体   繁体   English

如何在C#.net中检查数据集是否为空

[英]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. 我看到了这个问题-如何在C#.net中检查数据集是否为空-在有关C#面试问题的网站上。

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. 我是C#的新手,我认为这还有更多。

1.) Because he specified the zero index of the tables property, is that an assumption that there is only 1 table in the dataset? 1.)因为他指定了tables属性的零索引,是不是假设数据集中只有1个表? If there is only 1 table, then I understand that this will work. 如果只有1张桌子,那么我知道这将起作用。

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? 2.)但是,如果有多个表,那么我是否正确地说上面的代码不会确定数据集是否为空?

If I am correct [#2], then would this be the way to determine whether the dataset is empty or not? 如果我是正确的[#2],那么这将是确定数据集是否为空的方法吗?

        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. Fill()方法返回添加的行数。

See DbDataAdapter.Fill Method (DataSet) 请参见DbDataAdapter.Fill方法(数据集)

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. 您是对的,如果表ds.Tables[0].Rows.Count有多个表,则该测试无效。

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. 如果要检查数据集的所有表是否为空,则应遍历所有表,并查看是否存在任何数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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