linq to accept nullable value [closed]
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 //...
}
}
精彩评论