Linq接受可空值


 var menuItems = from c in xMenuElement.Elements("GlobalNavigation").Elements("PrimaryLink")
                 where c.Element("SecondaryLink").Element("LeftMenu").Element("NavLinks").Element("LinkID").Value.Trim() == "sad1" 
                 select c;

试试这个,这个技巧可以重复多次

var menuItems = from c in xMenuElement.Elements("GlobalNavigation").Elements("PrimaryLink")
                let secondaryLink = c.Element("SecondaryLink")
                where secondaryLink != null 
                   && secondaryLink.Element("LeftMenu").Element("NavLinks").Element("LinkID").Value.Trim() == "sad1"
                select c;

否则你可以创建一个方法:

var menuItems = from c in xMenuElement.Elements("GlobalNavigation").Elements("PrimaryLink")
                let linkId = GetLinkId(c)
                where linkId != null 
                select c;
string GetLinkId(XElement element)
{
    var secondaryLink = element.Element("SecondaryLink");
    if (secondaryLink == null) return null;
    var leftMenu = secondaryLink.Element("LeftMenu");
    if (leftMenu== null) return null;
    // ...
    return linkId.Value;
}

如果你仍然得到一个空引用异常,它可能是你的源有问题。

var globalNav = xMenuElement.Elements("GlobalNavigation");
if (globalNav != null)
{
    var primaryLinks = globalNav.Elements("PrimaryLink");
    if (primaryLinks != null)
    {
           var menuItems = from c in primaryLinks //...
    }
}

相关内容

  • 没有找到相关文章

最新更新