问题
I have a Web.sitemap file using the siteMapNode
elements in XML. I have added custom attributes to each tag. I am trying to extract the value of the custom attribute id
.
I want to find a single siteMapNode
in the SiteMapNodeCollection
which matches the custom attribute id
. I am able to achieve this using a foreach
loop, but I want to use LINQ to make it short and sweet.
--DOESN'T WORK-- The function is as follows:
private SiteMapNode FindNodeById(SiteMapNodeCollection nodes, int siteMapNodeId)
{
return nodes
.Cast<SiteMapNode>()
.First(node => node["id"] == Convert.ToString(siteMapNodeId));
}
However, I receive an InvalidOperationException => Sequence contains no matching element
. If I switch from a custom attribute to default .NET attribute, such as URL (or title), I get the node back without a problem.
For example, this statement works without a problem for a node with the title
attribute which is set to 'Test':
--WORKS--
private SiteMapNode FindNodeById(SiteMapNodeCollection nodes, int siteMapNodeId)
{
return nodes
.Cast<SiteMapNode>()
.First(node => node.title == "Test");
}
Can anyone point me in the right direction as to what I am missing in order for the custom attribute value to get matched in the .First
lambda expression?
I appreciate any help.
Have a great weekend!
Craig
回答1:
Replace First with FirstOrDefault. But if it crashes then it means there are no elements that satisfy the condition, so the result will be null.
来源:https://stackoverflow.com/questions/9036029/sequence-contains-no-matching-element-return-sitemapnode-matching-custom-attri