首页 文章

似乎无法使用Linq与ASP.Net导航菜单

提问于
浏览
4

我有以下代码:

// 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;
            }
        }

我想要的是:

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

然后我可以设置 itemSelected 值,但它在 NavigationMenu.Items 上给出了一个错误 .

错误5无法找到源类型“System.Web.UI.WebControls.MenuItemCollection”的查询模式的实现 . '哪里'找不到 . 考虑明确指定范围变量'i'的类型 .

当我注释掉 where 子句时,我收到此错误:

错误22无法找到源类型“System.Web.UI.WebControls.MenuItemCollection”的查询模式的实现 . 找不到“选择” . 考虑明确指定范围变量'i'的类型 .

1 回答

  • 5

    我怀疑 NavigationMenu.Items 只实现 IEnumerable ,而不是 IEnumerable<T> . 要解决此问题,您可能需要调用 Cast ,这可以通过在查询中显式指定元素类型来完成:

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

    但是,您的查询被误导地命名 - 这是一系列事物,而不是单个项目 .

    我还建议使用StringComparison来比较字符串,而不是上限它们 . 例如:

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

    然后我会考虑使用扩展方法:

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

相关问题