在C#中,什么是测试如果数据集是空的最佳方法是什么? [英] In C#, what is the best way to test if a dataset is empty?
问题描述
我知道你可以看看row.count或tables.count,但是否有其他的方法来判断一个数据集是空的?
I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?
推荐答案
我建议是这样的: -
I would suggest something like:-
bool nonEmptyDataSet = dataSet != null &&
(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
编辑:我显著清理适当考虑之后,我觉得这是更清洁的code。非常感谢基思的为灵感关于使用。任何()的。
Edits: I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of .Any().
在与基思的建议路线,这里是这种方法的扩展方法版本: -
In line with Keith's suggestion, here is an extension method version of this approach:-
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();
}
}
请注意,因为基思正确地纠正我对他文章的评论,此方法将工作,即使数据集为空。
Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null.
这篇关于在C#中,什么是测试如果数据集是空的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!