We help IT Professionals succeed at work.

Adding items to a C# list incrementally

282 Views
Last Modified: 2017-03-13
I'm creating a SelectList and I want the values essentially to be x, then x-1, then x-1, then x-1 until x=y

            do {
            var list6 = new List<SelectListItem>            
            {             
            new SelectListItem{ Text="" + maxhours + "", Value = "" + maxhours + "", Selected = true }
             };
                maxhours = maxhours - 1;
               
            }
            while (maxhours != datediff);

            ViewData["ddlhours"] = list6;

Open in new window


This obviously doesnt work as
 ViewData["ddlhours"] = list6;
is out of the loop. What's the best approach here?
Comment
Watch Question

AndyAinscowFreelance programmer / Consultant
CERTIFIED EXPERT

Commented:
change
            do {
            var list6 = new List<SelectListItem>            
to
            var list6 = new List<SelectListItem>            
            do {

ps.  and add the new item to the list inside your loop - you aren't doing that in your code snippet
Mike MillerSoftware Engineer

Author

Commented:
So like:

            var list6 = new List<SelectListItem>
            do
            {
                new SelectListItem { Text = "" + maxhours + "", Value = "" + maxhours + "", Selected = true };
                maxhours = maxhours - 1;
            }
            while (maxhours != datediff);
            ViewData["ddlhours"] = list6;

Open in new window


????

That gets me

A new expression requires (), [], or {} after type

On:

var list6 = new List<SelectListItem>

Open in new window

Freelance programmer / Consultant
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Mike MillerSoftware Engineer

Author

Commented:
Nice. I was so close at one point. Thanks for the extra eyes!
CERTIFIED EXPERT
Top Expert 2010

Commented:
I think this approach would be clearer:

for(var i = datediff; i < maxhours; i++)
{
   var li = new SelectListItem { Text = "" + i + "", Value = "" + i + "" };
   if(somecondition)
   {
        li.Selected = true;
    }
    list6.Add(li);
}

Open in new window


If you need the list items in reverse order, just change the loop:

for(var i = maxhours; i > datediff; i--)

Open in new window

Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.