我知道你可以查看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();
}
}
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();
由于扩展方法总是由编译器扩展,因此即使要检查的数据集为 null,这也可以正常工作。
在编译时,会进行以下更改:
ds.IsNotEmpty();
//becomes
DataSetExtensions.IsNotEmpty( ds );
#region Extension methods
public static class ExtensionMethods
{
public static bool IsEmpty(this DataSet dataSet)
{
return dataSet == null || dataSet.Tables.Count == 0 || !dataSet.Tables.Cast<DataTable>().Any(i => i.Rows.Count > 0);
}
}
#endregion