简体   繁体   中英

Nullable type and .HasValue still throws a Null Exception

I have a class describing the various Phones stored. Sometimes the Importance property can be null. Here is the class

public class PhoneTypeListInfo
{
    public string AccountNum { get; set; }
    public int PhoneType { get; set; }
    public string PhoneNum { get; set; }

    public int Importance { get; set; }
}

I have defined a function that will return a PhoneTypeListInfo if the Phone number and account number match a given set of values.

    protected PhoneTypeListInfo RetrievePhoneType(string info, string acctNumber)
    {
        PhoneTypeListInfo type = xPhoneTypeList.Where(p => p.PhoneNum == info && p.AccountNum == acctNumber).FirstOrDefault();

        return type;
    }

This all works great. The problem I'm having is with the linq query below.

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>();
xAccountPhones = (from x in xAccountStuff
                  where x.Media == "Phone"
                  let p = RetrievePhoneType(x.Info, acct.AccountNumber)
                  let xyz = x.Importance = (p.Importance as int?).HasValue ? p.Importance : 0
                  orderby p.Importance descending
                  select x).ToList();

What I am doing above is attempting to use a different class that has a different composition, except for obtaining the 'Importance' property from the PhoneTypeListInfo.

My question ultimately is, What do I need to do to allow p.Importance to be null, and set it to 0 if it is null, making x.Importance 0 as well.

It is not that p.Importannce that is null, but p itself. That is the thing you need to check for null first. If you are using C# 6 you can use the ?. operator. You can also smiplifiy the logic of (p.Importance as int?).HasValue ? p.Importance : 0 (p.Importance as int?).HasValue ? p.Importance : 0 to p.Importance ?? 0 p.Importance ?? 0 . Combining both you get

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>();
xAccountPhones = (from x in xAccountStuff
                         where x.Media == "Phone"
                         let p = RetrievePhoneType(x.Info, acct.AccountNumber)
                         let xyz = x.Importance = p?.Importance ?? 0
                         orderby p?.Importance descending
                         select x).ToList();

Use the ternary operator. Replace p.Importance with (null==p) ? 0 : p.Importance (null==p) ? 0 : p.Importance

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