Certain menu items need to be enabled only if files of a particular type exist in a specific listbox. There may be oodles of entries in that list box, but if even just one is of the file type in question, its menu item needs to be enabled. So, I've got the following code:
foreach (String pt in platypusTables)
{
if (pt.IndexOf("Duckbill") == 0)
{
menuItemSEND_Duckbills.Enabled = true;
}
if (pt.IndexOf("Platypus") == 0)
{
menuItemSEND_Platypi.Enabled = true;
}
listBoxWork.Items.Add(pt);
}
The problem is that the menu items may be enabled hundreds of times. I would prefer the elegance of being set once and once only, but can't figure out a sensible way to accomplish that. I could do this:
foreach (String pt in platypusTables)
{
if ((pt.IndexOf("Duckbill") == 0) && (!(menuItemSEND_Duckbills.Enabled)))
{
menuItemSEND_Duckbills.Enabled = true;
}
if ((pt.IndexOf("Platypus") == 0) && (!(menuItemSEND_Platypi.Enabled)))
{
menuItemSEND_Platypi.Enabled = true;
}
listBoxWork.Items.Add(pt);
}
...but I doubt that is any more performant, maybe less so. Am I stuck with the menu items being potentially enabled time and again, or is there a solution to this conundrum?
You could scan the collection for any strings starting with each type you're looking for. The call to Any()
will stop when it finds a match, and you're enabling each menu at most once.
menuItemSEND_Duckbills.Enabled = platypusTables.Any(p => p.StartsWith("Duckbill"));
menuItemSEND_Platypi.Enabled = platypusTables.Any(p => p.StartsWith("Platypus"));
listBoxWork.DataSource = platypusTables;
I'm not sure how performant this would be, since you're scanning the same collection multiple times for the first occurrence of each string. I suppose it depends on how large the collection of strings is, and how many menu items you're enabling this way.