In C#, what is the best way to test if a dataset is empty?

后端 未结 6 804
無奈伤痛
無奈伤痛 2021-01-12 13:59

I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?

6条回答
  •  日久生厌
    2021-01-12 14:29

    I think this is a place where you could use an extension method in C# 3 to improve legibility.

    Using kronoz's idea...

    public static bool IsNotEmpty ( this dataset ) 
    {
        return dataSet != null && (
            from DataTable t in dataSet.Tables 
            where t.Rows.AsQueryable().Any()
            select t).AsQueryable().Any();
    }
    
    //then the check would be
    DataSet ds = /* get data */;
    
    ds.IsNotEmpty();
    

    Due to the fact that extension methods are always expanded by the compiler this will even work if the dataset being checked is null.

    At compile time this is changed:

    ds.IsNotEmpty();
    
    //becomes
    
    DataSetExtensions.IsNotEmpty( ds );
    

提交回复
热议问题