假设表格上有4个按钮;每隔5秒,这些按钮的背景颜色会随机变化(但它也可以保持不变) 我怎么才能得到改变背景的按钮?
List<Button> oldList;
oldList = new List<Button>();
foreach (Button item in Controls.OfType<Button>())
{
//First we catch all the buttons' instances at for e.g 12:00
oldList.Add(item);
}
buttonsChangeColor(); //Five seconds later some buttons change their bg color
List<Button> newList = new List<Button>();
foreach (Button item in Controls.OfType<Button>())
{
//2nd we catch all the buttons' instances at for e.g 12:05 after some of theme changed color
newList.Add(item);
}
//HOW CAN I COMPARE THESE 2 LISTS BASED ON THE BACKGROUNDCOLOR ? If it has changed or not
答案 0 :(得分:2)
这应该有效
var changed = oldList.Zip(newList, (old, new) => new { Old = old, New = new })
.Where(old.BackColor != new.BackColor);
Enumerable.Zip
按元素对两个集合进行对。如果您只修改了颜色,则订单不应更改 - 因此就足够了。
答案 1 :(得分:1)
由于oldList
和newList
中按钮的实例相同,因此您需要记住旧背景颜色,以便将它们与新背景颜色进行比较。
以下内容应该有效:
var oldList = Controls.OfType<Button>().ToDictionary(btn => btn, btn => btn.BackColor);
buttonsChangeColor();
var changedBackgrounds = Controls.OfType<Button>()
.Where(btn => oldList[btn] != btn.BackColor).ToList();