开发者

linq to accept nullable value [closed]

开发者 https://www.devze.com 2023-02-28 06:13 出处:网络
开发者_如何学GoIt's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form.
开发者_如何学Go It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.
 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;


Try this, this technique can be repeated multiple times

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;

Otherwise you can create a Method:

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;
}

If you are still getting a null reference exception it might be your source that has the issue.

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

精彩评论

暂无评论...
验证码 换一张
取 消