How to check a var for null value?

∥☆過路亽.° 提交于 2019-12-23 07:01:28

问题


I am using PetaPoco Micro-ORM with C# 4.0.

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?


回答1:


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

.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.




回答2:


var result = db.SingleOrDefault<TdUsers>(getUserQuery);

In above code SingleOrDefault will return null vale or the specified generic type(it's known on runtime).

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
}



回答3:


You could do:

result.ToList() // Convert result to a list

if (result.Any()) {
   // result is not null
}



回答4:


 var v = result.ToList();

now check

if (v.Count > 0)


来源:https://stackoverflow.com/questions/10753661/how-to-check-a-var-for-null-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!