LINQ : Check for NullReferenceException
In the following code, How can I check for null reference exception in a "good practice" way?
if (primaryMenu.ChildNodes.Any(p=>VirtualPathUtility.GetFileName(p.SiteURL).Equals(selectedPage)))
{
primaryMenuTab.Attributes.Add("class", "current");
}
The way I am doing it currently is (But JetBrain ReSharper doesnt't wana accept it and keep warning me on the following part : VirtualPathUtility.GetFileName(p.SiteURL) which is understandable),
if (primaryMenu.ChildNodes.Any(p=> p.SiteURL != null && VirtualPathUtility.GetFileName(p.SiteURL).Equals(selectedPage)))
{
primaryMen开发者_运维技巧uTab.Attributes.Add("class", "current");
}
Where Menus have the following structure,
public class MultiLevelMenuNodeList
{
public string Name { get; set; }
public string Permission { get; set; }
public string SiteURL { get; set; }
public string Visibility { get; set; }
public List<SingleLevelMenuNodeList> ChildNodes { get; set; }
}
public class SingleLevelMenuNodeList
{
public string Name { get; set; }
public string Permission { get; set; }
public string SiteURL { get; set; }
public string Visibility { get; set; }
public string TabPosition { get; set; }
}
Thanks in advance for suggestions and tips. I am kinda getting addicted to stackoverflow:)
A simple solution is to just use == which is null-safe:
if (primaryMenu.ChildNodes.Any(p =>
VirtualPathUtility.GetFileName(p.SiteURL) == selectedPage))
(That's assuming GetFileName
itself can cope with null input; otherwise put your first null check back in.)
精彩评论