Can't seem to use Linq with ASP.Net Navigation menu

别来无恙 提交于 2019-12-10 15:55:48

问题


I have the following piece of code:

        // Iterate through the root menu items in the Items collection.
        foreach (MenuItem item in NavigationMenu.Items)
        {
            if (item.NavigateUrl.ToLower() == ThisPage.ToLower())
            {
                item.Selected = true;
            }
        }

What I'd like is:

var item = from i in NavigationMenu.Items
           where i.NavigateUrl.ToLower() == ThisPage.ToLower()
           select i;

Then I can set the Selected value of item, but it gives me an error on the NavigationMenu.Items.

Error 5 Could not find an implementation of the query pattern for source type 'System.Web.UI.WebControls.MenuItemCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'i'.

When I comment out the where clause, I get this error:

Error 22 Could not find an implementation of the query pattern for source type 'System.Web.UI.WebControls.MenuItemCollection'. 'Select' not found. Consider explicitly specifying the type of the range variable 'i'.


回答1:


I suspect NavigationMenu.Items only implements IEnumerable, not IEnumerable<T>. To fix this, you probably want to call Cast, which can be done by explicitly specifying the element type in the query:

var item = from MenuItem i in NavigationMenu.Items
           where i.NavigateUrl.ToLower() == ThisPage.ToLower()
           select i;

However, your query is named misleadingly - it's a sequence of things, not a single item.

I'd also suggest using a StringComparison to compare the strings, rather than upper-casing them. For example:

var items = from MenuItem i in NavigationMenu.Items
            where i.NavigateUrl.Equals(ThisPage, 
                                 StringComparison.CurrentCultureIgnoreCase)
            select i;

I'd then consider using extension methods instead:

var items = NavigationMenu.Items.Cast<MenuItem>()
            .Where(item => item.NavigateUrl.Equals(ThisPage, 
                                 StringComparison.CurrentCultureIgnoreCase));


来源:https://stackoverflow.com/questions/6954163/cant-seem-to-use-linq-with-asp-net-navigation-menu

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