【发布时间】:2008-09-06 21:02:43
【问题描述】:
我知道您可以查看 row.count 或 tables.count,但是还有其他方法可以判断数据集是否为空?
【问题讨论】:
我知道您可以查看 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 在他的帖子的 cmets 中正确纠正我的那样,即使数据集为空,此方法也可以工作。
【讨论】:
怎么了
(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 );
【讨论】:
为了清楚起见,您首先需要查看所有数据表,然后查看每个数据表的行数。
【讨论】:
#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
【讨论】: