How do I shorten this generic list?

∥☆過路亽.° 提交于 2019-12-22 12:51:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!