似乎不能使用Linq与ASP.Net导航菜单 [英] Can't seem to use Linq with ASP.Net Navigation menu
问题描述
我有下面一段代码:
//迭代通过Items集合根菜单项。
的foreach(在NavigationMenu.Items菜单项的项目)
{
如果(item.NavigateUrl.ToLower()== ThisPage.ToLower())
{
项。选择= TRUE;
}
}
我想的是:
VAR项=从我NavigationMenu.Items
,其中i.NavigateUrl.ToLower()== ThisPage.ToLower()
选择我;
然后我可以设置的选
价值项目
,但它给我的 NavigationMenu.Items
。
$ b错误$ b
错误5找不到
源类型'System.Web.UI.WebControls.MenuItemCollection查询模式的实现。 去哪儿
未找到。考虑显式指定范围内
变量'我'的类型。
块引用>
当我注释掉
其中,
条款,我得到这个错误:
错误22找不到查询模式的实现
源类型'System.Web.UI.WebControls.MenuItemCollection。 选择'
未找到。考虑显式指定范围内
变量'我'的类型。
块引用>
解决方案我怀疑
NavigationMenu.Items
只实现的IEnumerable
,而不是的IEnumerable< T>
。为了解决这个问题,你可能想调用演员
,它可以通过显式指定查询元素类型来完成:VAR项=从菜单项我NavigationMenu.Items
,其中i.NavigateUrl.ToLower()== ThisPage.ToLower()
选择我;
不过,您的查询是误导命名 - 它是的东西的序列,不是一个单一的项目。
我还建议使用的
StringComparison
比较字符串,而不是上层套管他们。例如:VAR项目从菜单项I =在NavigationMenu.Items
,其中i.NavigateUrl.Equals(ThisPage,
StringComparison.CurrentCultureIgnoreCase)
选择我;
我会再考虑使用扩展方法来代替:
VAR项目= NavigationMenu.Items.Cast<&菜单项GT;()
。凡(项目=> item.NavigateUrl.Equals(ThisPage,
StringComparison .CurrentCultureIgnoreCase));
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 ofitem
, but it gives me an error on theNavigationMenu.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 implementsIEnumerable
, notIEnumerable<T>
. To fix this, you probably want to callCast
, 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));
这篇关于似乎不能使用Linq与ASP.Net导航菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!