怎样缩短这个泛型列表? [英] How do I shorten this generic list?
本文介绍了怎样缩短这个泛型列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题很简单:我怎样才能缩短这个代码更?
列表<按钮和GT; buttonList =新的List<按钮和GT;();
buttonList.Add(按钮1);
buttonList.Add(按钮2);
buttonList.Add(按钮3);
buttonList.Add(将Button4);
buttonList.Add(button5);
buttonList.Add(button6);
buttonList.Add(button7);
buttonList.Add(按钮8);
buttonList.Add(按钮9);
解决方案
如果你有存储在一些控制的您的按钮 控制
集合(比方说,一个表格
或面板
),那么你可以使用:
//这里`this`应该是一个'Form`
名单,LT按钮> buttonList = this.Controls.OfType<按钮和GT;()
.OrderBy(B = GT; b.Name)
.ToList();
在这种情况下,你可能有你的方法,返回按钮的枚举,存放一些容器控件中:
公开的IEnumerable<按钮和GT; GetButtons()
{
返回this.Controls.OfType&所述;按钮方式>()的OrderBy(B => b.Name);
//返回this.panel1.Controls.OfType<按钮和GT;()排序依据(B = GT; b.Name)。
//其实你遇到内
}
<你的按钮任何容器控件p >你可以使用它:
的foreach(键b在GetButtons())
{
/ / ...
}
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);
解决方案
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())
{
//...
}
这篇关于怎样缩短这个泛型列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文