我在这里通过阅读你的好答案来学习,从foreach循环中删除项目并不是一个好习惯,因为它是(并且我引用)"锯掉你所坐的分支".
我的代码当前从下拉列表中删除了文本,但实际项目仍然存在(仅显示文本).
换句话说,它不是删除,也可能是因为你无法从foreach循环中删除.
经过几个小时的尝试,我无法理解这种做法.
//For each checked box, run the delete code
for (int i = 0; i < this.organizeFav.CheckedItems.Count; i++)
{
//this is the foreach loop
foreach (ToolStripItem mItem in favoritesToolStripMenuItem.DropDownItems)
{
//This rules out seperators
if (mItem is ToolStripMenuItem)
{
ToolStripMenuItem menuItem = mItem as ToolStripMenuItem;
//This matches the dropdownitems text to the CheckedItems String
if (((ToolStripMenuItem)mItem).Text.ToString() == organizeFav.CheckedItems[i].ToString())
{
//And deletes the item
menuItem.DropDownItems.Remove(mItem);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它并没有删除,因为它在foreach循环中!我非常感谢您的帮助,如果有人能够了解这些代码,我会感到非常惊讶:)
亲切的问候
LINQ的乐趣!
// Loop through the checked items, same as you did.
foreach (var checkedItem in this.organizeFav.CheckedItems)
{
// Cast from IEnumerable to IEnumerable<T> so we can abuse LINQ
var matches = favoritesToolStripMenuItem.DropDownItems.Cast<ToolStripItem>()
// Only items that the Text match
.Where(item => item.Text == checkedItem.Text)
// Don't match separators
.Where(item => item is ToolStripMenuItem)
// Select the keys for the later .Remove call
.Select(item => item.Name);
// Loop through all matches
foreach (var key in matches)
{
// Remove them with the Remove(string key) overload.
favoritesToolStripMenuItem.Remove(key);
}
}
Run Code Online (Sandbox Code Playgroud)