我有以下代码:
// 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;
然后我可以设置 item
的 Selected
值,但是它在 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/