views:

43

answers:

2

Recently I wrote a piece of C# code utilizing a Lambda expression:

var dynMenu = new List<MenuItem>();
// some code to add menu items to dynMenu
if (!dynMenu.Any(x => x.Text == controller))
{ 
    // do something
}

While going thru my code, I discovered that each MenuItem itself has a property called ChildItems which happens to be of type MenuItemCollection. Intrigued, I figured I would replace my List of MenuItem with this MenuItemCollection.

Upon changing the first line to:

var dynMenu = new MenuItemCollection();

I noticed that this MenuItemCollection type has no Extension Methods like "Any<>", "All<>", "First<>", etc., etc. -- which I find strange.

Is there a way to utilize Lambda expressions here?

Should I just go back to using "List<<\MenuItem>"?

+3  A: 

MenuItemCollection is a .NET 1.1 class. It does not implement any of the generic collection interfaces, in particular, IEnumerable<MenuItem>.

Since this only implements IEnumerable and not IEnumerable<MenuItem>, all of the extension methods LINQ provides which require this don't work. However, you can get them back by doing:

if (dynMenu.Cast<MenuItem>().Any(x => x.Test == controller)) { // ...

The Cast extension method converts the IEnumerable to IEnumerable<T>, providing access to the other LINQ extension methods.

Reed Copsey
A ha. I hadn't realized that is was .NET 1.1 -- So should I not be using it? I'm basically trying to build a dynamically-constructed multi-nested navigation-bar in ASP.NET MVC and it seemed like a reasonable structure to use. (rather than invent my own...)
Pretzel
@Pretzel: It depends - I'd probably just use List<T> instead. If, however, you're going to have to create a MenuItemCollection eventually, sometimes it's easier to just use it up front (rare, though).
Reed Copsey
Hmmm... ok. I'll think about it. Thanks for the advice and the IEnumerable / Type lesson!
Pretzel
A: 

MenuItemCollection is a specialized collection and does not implement the IEnumerable Interface to use the Linq Extension Methods that you name above. I would just go back to the generic list as it has more functionality

runxc1 Bret Ferrier
It does implement IEnumerable, just not IEnumerable<T>.
Reed Copsey