c#将1-25写入列表框;简洁的方式来做到这一点?
问题描述:
C#是程序。c#将1-25写入列表框;简洁的方式来做到这一点?
我在写一个程序,它需要一个带有数字1-25的列表框作为条目。我确信有一个更简洁的方法来做到这一点。
我该如何简洁这段代码?
下面是当前的代码:
shiftListBox.Text = "";
shiftListBox.Items.Add("Random");
shiftListBox.Items.Add("1"); //is there a more concise way to write this- with a loop, for example?
shiftListBox.Items.Add("2");
shiftListBox.Items.Add("3");
shiftListBox.Items.Add("4");
shiftListBox.Items.Add("5");
shiftListBox.Items.Add("6");
shiftListBox.Items.Add("7");
shiftListBox.Items.Add("8");
shiftListBox.Items.Add("9");
shiftListBox.Items.Add("10");
shiftListBox.Items.Add("11");
shiftListBox.Items.Add("12");
shiftListBox.Items.Add("13");
shiftListBox.Items.Add("14");
shiftListBox.Items.Add("15");
shiftListBox.Items.Add("16");
shiftListBox.Items.Add("17");
shiftListBox.Items.Add("18");
shiftListBox.Items.Add("19");
shiftListBox.Items.Add("20");
shiftListBox.Items.Add("21");
shiftListBox.Items.Add("22");
shiftListBox.Items.Add("23");
shiftListBox.Items.Add("24");
shiftListBox.Items.Add("25");
答
您可以使用一个for循环:
shiftListBox.Items.Add("Random");
for (int i = 1; i < 26; i++)
{
shiftListBox.Items.Add(i);
}
答
使用迭代。或者LINQ。这是一个LINQ示例。
Enumerable.Range(1, 25).ToList().ForEach(x => shiftListBox.Items.Add(x));
不要忘记在代码顶部导入LINQ命名空间。
using System.Linq;
+2
我会写同样的方式。而不是ForEach()。Items.Add()部分,我只是简单地将它作为shiftListBox的DataSource。 –
+1
'Enumerable.Range'非常有用:) – Corey
你不高兴你不必写1-100000吗?一般来说,如果你发现自己重复这样的事情,你很可能做错了事情。 –
我知道,对吧? –