简体   繁体   English

如何检查ToolStripMenuItem DropDownItems中是否已存在项目?

[英]How do I check if items already exist in a ToolStripMenuItem DropDownItems?

items = File
    .ReadLines(RecentFiles)
    .Select(line => new ToolStripMenuItem()
    {
        Text = line
    })
    .ToArray();
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);

I want to check if the items exist already in the recentFilesToolStripMenuItem.DropDownItems 我想检查项目是否已经存在于recentFilesToolStripMenuItem.DropDownItems

If not exist add but if exist don't add. 如果不存在,则添加,但如果不存在,则不添加。

You basically have two collections: items & recentFilesToolStripMenuItem.DropDownItems 基本上,您有两个集合: itemsrecentFilesToolStripMenuItem.DropDownItems

Using Linq , you should be able to do 使用Linq ,您应该可以 an Except() 一个Except() a Where() to only add the difference between the two collections. 一个Where()仅添加两个集合之间的差异。

This is not tested. 这未经测试。

recentFilesToolStripMenuItem.DropDownItems.AddRange(items.Except(recentFilesToolStripMenuItem.DropDownItems)); recentFilesToolStripMenuItem.DropDownItems.AddRange(items.Except(recentFilesToolStripMenuItem.DropDownItems));

This is tested 经过测试

recentFilesToolStrip.DropDownItems.AddRange(
    items
    .Where(i => !recentFilesToolStrip.DropDownItems
                 .OfType<ToolStripMenuItem>()
                 .Select(t => t.Text).Contains(i.Text)
          ).ToArray()
);

SLaks comment refers to doing something like the following: SLaks评论指的是执行以下操作:

recentFilesToolStripMenuItems.DropDownItems.Clear();
recentFilesToolStripMenuItems.DropDownItems.AddRange(items);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM