简体   繁体   中英

c# write 1-25 to listbox; concise way to do this?

C# is program.

I am writing a program which requires a list box with numbers 1-25 as entries. I am certain there is a more concise way to do this.

How can I concise this code?

Here is current code:

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");

Use iteration. Or LINQ. Here's a LINQ sample.

Enumerable.Range(1, 25).ToList().ForEach(x => shiftListBox.Items.Add(x));

Don't forget to import the LINQ namespace at the top of your code.

using System.Linq;

You can use a for loop:

shiftListBox.Items.Add("Random");

for (int i = 1; i < 26; i++)
{
    shiftListBox.Items.Add(i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM