C# 如何检查var是否为空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10753661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check a var for null value?
提问by RKh
I am using PetaPoco Micro-ORM with C# 4.0.
我在 C# 4.0 中使用 PetaPoco Micro-ORM。
The code below retrieves a single row from the database:
下面的代码从数据库中检索一行:
var result = db.SingleOrDefault<TdUsers>(getUserQuery);
I would like to check whether or not the result contains any rows, and whether is null. What is the best way to do this?
我想检查结果是否包含任何行,以及是否为空。做这个的最好方式是什么?
采纳答案by Parv Sharma
if (result == null || result.Count() == 0) {
// Checks whether the entire result is null OR
// contains no resulting records.
}
I think the problem is not in your check for null, because linq is lazy loading. Your error is in using the expression db.SingleOrDefault<TdUsers>(getUserQuery);.
我认为问题不在于您的检查null,因为 linq 是延迟加载。您的错误在于使用表达式db.SingleOrDefault<TdUsers>(getUserQuery);。
.Single<T>(expression)does not return null - it errors if the result returns no values.
.SingleOrDefault<T>(expression), however, returns a null value if the expression results in no values - and therefore is best combined with an if (result == null)type check, as you're using here.
.Single<T>(expression)不返回 null - 如果结果没有返回值,则会出错。
.SingleOrDefault<T>(expression),但是,如果表达式没有结果,则返回空值 - 因此最好与if (result == null)类型检查结合使用,正如您在此处使用的那样。
回答by Romil Kumar Jain
var v = result.ToList();
now check
现在检查
if (v.Count > 0)
回答by Darren
You could do:
你可以这样做:
result.ToList() // Convert result to a list
if (result.Any()) {
// result is not null
}
回答by shanky
var result = db.SingleOrDefault<TdUsers>(getUserQuery);
In above code SingleOrDefault will return null vale or the specified generic type(it's known on runtime).
在上面的代码中 SingleOrDefault 将返回空值或指定的泛型类型(它在运行时已知)。
Inorder to check whether the returned values is null or not you can simply use
为了检查返回的值是否为空,您可以简单地使用
if(result!=null)
{
//do your code stuff
}
else
{
//stuff do be done in case where result==null
}

