在C#中,测试数据集是否为空的最佳方法是什么?

我知道你可以查看row.count或tables.count,但还有其他方法可以判断数据集是否为空?

我会建议像: –

bool nonEmptyDataSet = dataSet != null && (from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); 

编辑:经过充分考虑,我已经大大清理了代码,我认为这更清洁。 非常感谢Keith关于使用.Any()的灵感。

根据Keith的建议,这是这种方法的扩展方法版本: –

 public static class ExtensionMethods { public static bool IsEmpty(this DataSet dataSet) { return dataSet == null || !(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); } } 

请注意,正如Keith在他的post的评论中正确地纠正了我,即使数据集为空,这种方法也会起作用。

怎么了?

(aDataSet.Tables.Count == 0)

我已经为此创建了一个小的静态util类

下面的代码应该像英文句子一样。

  public static bool DataSetIsEmpty(DataSet ds) { return !DataTableExists(ds) && !DataRowExists(ds.Tables[0].Rows); } public static bool DataTableExists(DataSet ds) { return ds.Tables != null && ds.Tables.Count > 0; } public static bool DataRowExists(DataRowCollection rows) { return rows != null && rows.Count > 0; } 

我会把类似下面的代码放到代码中并完成它。 编写可读代码确实很重要。

  if (DataAccessUtil.DataSetIsEmpty(ds)) { return null; } 

我认为这是一个可以在C#3中使用扩展方法来提高易读性的地方。

使用kronoz的想法……

 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(); 

由于扩展方法总是由编译器扩展,因此如果被检查的数据集为空,这甚至可以工作。

在编译时,这会改变:

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

要清楚,首先需要查看所有DataTable,然后查看每个DataTable的行数。

 #region Extension methods public static class ExtensionMethods { public static bool IsEmpty(this DataSet dataSet) { return dataSet == null || dataSet.Tables.Count == 0 || !dataSet.Tables.Cast().Any(i => i.Rows.Count > 0); } } #endregion