开发者

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

开发者 https://www.devze.com 2023-03-26 06:54 出处:网络
I have the following piece of code: // Iterate through the root menu items in the Items collection. foreach (MenuItem item in NavigationMenu.Items)

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'.


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消