简体   繁体   English

检查空变量C#

[英]check null variable C#

I have created a variable that checks if a row in a database exists. 我创建了一个变量,用于检查数据库中是否存在行。 However when I put the variable in an if statement to check if it's null and the variable is null it always goes to else instead of continuing the if statement. 但是,当我将变量放在if语句中以检查它是否为null且该变量为null时,它总是转到else而不是继续执行if语句。

Is there another way of checking if a variable is null instead of == null ? 还有另一种检查变量是否为null而不是== null吗?

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id);
if (following == null)
{
    using (Html.BeginForm("Followruser", "Users"))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        @Html.Hidden("Id", Id)
        <input type="submit" value="follow" class="btn btn-default" />
    }
}
else
{
    using (Html.BeginForm("unfollowruser", "Users"))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        @Html.Hidden("Id", Id)
        <input type="submit" value="following" class="btn btn-default" />
    }

}

The Where operator will never return null . Where运算符将永远不会返回null It is also the wrong method to use if you simply want to check if a record exists. 如果您只想检查记录是否存在,这也是使用错误的方法。 I'd use Any instead. 我会改用Any

bool following = objCtx.Followusers.Any(
    c => c.User1ID == currentUser.Id || c.User2ID == cus.Id);

Change it to: 更改为:

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id).SingleOrDefault();

That should return NULL if no row is found. 如果找不到行,则应返回NULL。

The object returned is never null, it's value might be though. 返回的对象永远不会为null,但是其值可能是null。 Use 'FirstOrDefault()' to make the result null if there is none: 如果没有结果,请使用“ FirstOrDefault()”将结果设为空:

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id).FirstOrDefault();

Or ask the result if it has any values: 或询问结果是否具有任何值:

if(following.Any())

If you want to keep what you have given, you can also count number of values returned by the predicate. 如果要保留给定的值,还可以计算谓词返回的值数。

if (following != null && following.Count < 1)

This should work for you I think. 我认为这应该对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM