c# – 似乎无法使用Linq和ASP.Net导航菜单
作者:互联网
我有以下代码:
// 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,navigationbar 来源: https://codeday.me/bug/20190621/1253668.html