简体   繁体   中英

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.

Is there another way of checking if a variable is null instead of == 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 . It is also the wrong method to use if you simply want to check if a record exists. I'd use Any instead.

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.

The object returned is never null, it's value might be though. Use 'FirstOrDefault()' to make the result null if there is none:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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