Sequence contains no matching element - Return SiteMapNode matching custom attribute using LINQ

做~自己de王妃 提交于 2019-12-14 04:19:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!