How to check empty DataTable

后端 未结 8 633
孤城傲影
孤城傲影 2020-12-10 10:15

I have a DataSet where I need to find out how many rows has been changed using the following code:

dataTable1 = dataSet1.Tables[\"FooTable\"].Ge         


        
8条回答
  •  萌比男神i
    2020-12-10 10:47

    Don't use rows.Count. That's asking for how many rows exist. If there are many, it will take some time to count them. All you really want to know is "is there at least one?" You don't care if there are 10 or 1000 or a billion. You just want to know if there is at least one. If I give you a box and ask you if there are any marbles in it, will you dump the box on the table and start counting? Of course not. Using LINQ, you might think that this would work:

    bool hasRows = dataTable1.Rows.Any()
    

    But unfortunately, DataRowCollection does not implement IEnumerable. So instead, try this:

    bool hasRows = dataTable1.Rows.GetEnumerator().MoveNext()
    

    You will of course need to check if the dataTable1 is null first. if it's not, this will tell you if there are any rows without enumerating the whole lot.

提交回复
热议问题