views:

268

answers:

4

I have a MenuStrip with lots of items and am trying to have on event they all subscribe to so I am trying to do menuStrip1.Items.OfType<ToolStripMenuItem>(); and for each one I do this:

menuitem.Click += new EventHandler(MenuItem_Click);

The problem is there is a ToolStripSeperatorItem which inherits off ToolStripMenuItem and that appears is my list of items and errors because it does not have a Click event.

How can I not include these in my OfType method?

+2  A: 
menuStrip1.Items.OfType<ToolStripMenuItem>()
                .Where(i => i.GetType() == typeof(ToolStripMenuItem))
LukeH
Items does not have a Where method
Jon
You're right. The `Items` collection only implements `IEnumerable`, not `IEnumerable<T>`, so we still need the `OfType` call in there too.
LukeH
A: 

Maybe like this:

menuStrip1.Items
    .OfType<ToolStripMenuItem>()
    .Except(menuStrip1.Items.OfType<ToolStripSeparatorItem>())
Kyralessa
+1  A: 
menuStrip1.Items.OfType<ToolStripMenuItem>().Where(it => it.GetType() == typeof(ToolStripMenuItem));

It seems kind of redundant, but by doing both, you maintain the return type.

Michael Bray
A: 
menuStrip1.Items
 .Cast<ToolStripMenuItem>()
 .Where(i => i.GetType() == typeof(ToolStripSeparatorItem));

Because you don't need an implicit cast and comparision (OfType) which is basically slower then explicit cast with Cast

George Polevoy