c# - 似乎无法将 Linq 与 ASP.Net 导航菜单一起使用

标签 c# linq navigationbar

我有以下代码:

        // 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 上给我一个错误。

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

当我注释掉 where 子句时,出现此错误:

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

最佳答案

我怀疑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));

关于c# - 似乎无法将 Linq 与 ASP.Net 导航菜单一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6954163/

相关文章:

c# - 使用 LINQ GroupBy() 从数据库获取唯一项目的强类型列表

c# - 以下两个语句有什么区别?

javascript - 显示/隐藏一个 div 有条件地点击另一个 div 中的链接

ios - 如何在导航栏中添加pageControl和标题?

c# - 在自定义 TypeFormatter 中使用 RegisterWebApiRequest 时出现 SimpleInjector.ActivationException

c# - 使用 dapper 选择

c# - 带分页的 gridview 中的搜索框

c# - System.Core.dll 中发生类型为 'System.StackOverflowException' 的未处理异常

c# - 在 LINQ 中连接 2 个具有不同长度的列表

javascript - 如何使 div 充当滚动条句柄