You must Sign In to post a response.
  • Category: LINQ

    How to check null value in LINQ


    Are you looking for a way to check null value in LINQ ? then read this thread to know how to do it



    Find my code below. I have tried these to check null value,


    // objDriveline = objDatabase.Drivelines.Where(con => con.DrivelineId == DrivelineId).SingleOrDefault();

    //objDriveline = objDatabase.Drivelines.Where(con => con.DrivelineId == DrivelineId).DefaultIfEmpty(new Driveline()).Single();


    But didn't worked out.Any help will be appreciated. Please do not send me the link, I have checked couple of sites. Thank you.





    public Driveline GetDriveline(int DrivelineId)
    {
    Driveline objDriveline = new Driveline();
    if (DrivelineId != 0)
    {
    using (NewEntities objDatabase = new NewEntities (DatabaseConnString))
    {
    try
    {

    bjDriveline = objDatabase.Drivelines.SingleOrDefault(con => con.DrivelineId == DrivelineId);

    }
    catch (Exception ex)
    {
    throw new COODataCouldNotDisplay(ex.InnerException);
    }

    }

    }
    return objDriveline;
    }
  • #745983
    If the value you are comparing is null then you can try handling this as



    objDriveline = objDatabase.Drivelines.Where(con => con.DrivelineId equals (int?)DrivelineId).DefaultIfEmpty(new Driveline()).Single();




    Thanks & Regards
    Anil Kumar Pandey
    Microsoft MVP, DNS MVM

  • #745992
    see below ways to check null in LINQ
    1. check value is NULL

    var titleless = items.Where(x => x.Title == null);

    2. Or you may check null separately as below

    string title = null;
    var titleless = items.Where(x => x.Title == title);

    3. here is another way

    var titleless = items.Where(
    x => title == null ? x.Title == null : x.Title == title);

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]


  • Sign In to post your comments