开发者

MenuItemCollection vs. List<MenuItem>

开发者 https://www.devze.com 2023-01-04 12:19 出处:网络
Recently I wrote a piece of C# code utilizing a Lambda expression: var dynMenu = new List<MenuItem>();

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 MenuItemCollec开发者_如何学运维tion 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>"?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号