似乎无法使用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
上给出了一个错误。
错误5无法找到源类型“System.Web.UI.WebControls.MenuItemCollection”的查询模式的实现。 ‘哪里’找不到。 考虑明确指定范围变量’i’的类型。
当我注释掉where
子句时,我收到此错误:
错误22无法找到源类型“System.Web.UI.WebControls.MenuItemCollection”的查询模式的实现。 找不到“选择”。 考虑明确指定范围变量’i’的类型。
我怀疑NavigationMenu.Items
只实现IEnumerable
,而不是IEnumerable
。 要解决此问题,您可能希望调用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