簡體   English   中英

如何在C#.net中檢查數據集是否為空

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

我看到了這個問題-如何在C#.net中檢查數據集是否為空-在有關C#面試問題的網站上。

有人回答:

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.
}

我是C#的新手,我認為這還有更多。

1.)因為他指定了tables屬性的零索引,是不是假設數據集中只有1個表? 如果只有1張桌子,那么我知道這將起作用。

2.)但是,如果有多個表,那么我是否正確地說上面的代碼不會確定數據集是否為空?

如果我是正確的[#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" );
        }

問候...丹

您可以通過它進行檢查。

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

    return true;
}

我希望這會起作用,您可以使用此方法進行檢查

Fill()方法返回添加的行數。

請參見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
         }
    }
}

您是對的,如果表ds.Tables[0].Rows.Count有多個表,則該測試無效。

但是,如果表存在,則數據集不為空。 如果要檢查數據集的所有表是否為空,則應遍歷所有表,並查看是否存在任何數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM