Member_2_1242703
asked on
Adding items to a C# list incrementally
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
This obviously doesnt work as
ViewData["ddlhours"] = list6;
is out of the loop. What's the best approach here?
do {
var list6 = new List<SelectListItem>
{
new SelectListItem{ Text="" + maxhours + "", Value = "" + maxhours + "", Selected = true }
};
maxhours = maxhours - 1;
}
while (maxhours != datediff);
ViewData["ddlhours"] = list6;
This obviously doesnt work as
ViewData["ddlhours"] = list6;
is out of the loop. What's the best approach here?
ASKER
So like:
????
That gets me
On:
var list6 = new List<SelectListItem>
do
{
new SelectListItem { Text = "" + maxhours + "", Value = "" + maxhours + "", Selected = true };
maxhours = maxhours - 1;
}
while (maxhours != datediff);
ViewData["ddlhours"] = list6;
????
That gets me
A new expression requires (), [], or {} after type
On:
var list6 = new List<SelectListItem>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Nice. I was so close at one point. Thanks for the extra eyes!
I think this approach would be clearer:
If you need the list items in reverse order, just change the loop:
for(var i = datediff; i < maxhours; i++)
{
var li = new SelectListItem { Text = "" + i + "", Value = "" + i + "" };
if(somecondition)
{
li.Selected = true;
}
list6.Add(li);
}
If you need the list items in reverse order, just change the loop:
for(var i = maxhours; i > datediff; i--)
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