简体   繁体   中英

Handle null element in linq

I'm reading data from an XML. I'm running into an issue where a value is null and I'm not sure the best way to handle it. Below is a snippet of code. The Street Address 2 does not exist in this XML but does in others so I need to make it dynamic enough to handle both instances.

var storeInfo = storeRows.Descendants("Store").Select(s => new
{
    storeName = s.Element("StoreName").Value,
    streetAddress1 = s.Element("StreetAddress1").Value,
    streetAddress2 = s.Element("StreetAddress2").Value
});
{
    foreach (var st in storeInfo)
    {
        alStoreName.Add(st.storeName.ToString());
        alStreet1.Add(st.StreetAddress1.ToString());
        alStreet2.Add(st.StreetAddress2.ToString());
    }
}

Use explicit cast instead of accessing Value property

var storeInfo = storeRows.Descendants("Store").Select(s => new
{
    storeName = (string)s.Element("StoreName"),
    streetAddress1 = (string)s.Element("StreetAddress1"),
    streetAddress2 = (string)s.Element("StreetAddress2")
});

This will return null if the element does not exist.

In addition I recommend you to create a class to encapsualate store info instead of storing information in different lists. Then just have a list of storeInfo 's instead of a list of anonymous type:

var storeInfo = storeRows.Descendants("Store").Select(s => new StoreInfo
{
    storeName = (string)s.Element("StoreName"),
    streetAddress1 = (string)s.Element("StreetAddress1"),
    streetAddress2 = (string)s.Element("StreetAddress2")
});

You should use (string)XElement explicit cast instead of Value property. It will return null when element doesn't exist.

streetAddress2 = (string)s.Element("StreetAddress2")

You can cast XElement to most of the primitive types, string , DateTime , Guid and Nullable<T> of above. See full list here: XElement Type Conversions

The same rule applies to XAttribute .

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