问题
My question is simply: how can I shorten this code even more?
List<Button> buttonList = new List<Button>();
buttonList.Add(button1);
buttonList.Add(button2);
buttonList.Add(button3);
buttonList.Add(button4);
buttonList.Add(button5);
buttonList.Add(button6);
buttonList.Add(button7);
buttonList.Add(button8);
buttonList.Add(button9);
回答1:
If you've got your buttons stored in some control's Controls collection (say, a Form or a Panel), then you could use:
//here `this` is supposed to be a `Form`
List<Button> buttonList = this.Controls.OfType<Button>()
.OrderBy(b=>b.Name)
.ToList();
In this case you may have your method, returning an enumerable of buttons, stored within some container control:
public IEnumerable<Button> GetButtons()
{
return this.Controls.OfType<Button>().OrderBy(b => b.Name);
//return this.panel1.Controls.OfType<Button>().OrderBy(b => b.Name);
//actually any container control you're having your buttons within
}
and you may use it:
foreach(Button b in GetButtons())
{
//...
}
回答2:
Try a collection initializer:
List<Button> buttonList = new List<Button>()
{
button1,
button2,
button3,
button4,
button5,
button6,
button7,
button8,
button9
}
回答3:
You can use a collection initializer:
var buttonList = new List<Button>
{
button1, button2, button3,
//...
};
回答4:
You can use a collection intializer:
List<Button> buttonList = new List<Button>
{
button1,
button2,
button3,
button4,
button5,
button6,
button7,
button8,
button9,
}
来源:https://stackoverflow.com/questions/14491982/how-do-i-shorten-this-generic-list