Tuesday, March 1, 2011

Get checked values from array

Hello

I'm using mvc and I'm trying to loop through a array of checkboxes, but how do I exclude the ones that are "false" in that list?

for(int i = 0; i < TimeRange1.Length; i++)
        {
          if(TimeRange1[i] == "false" ....??)
        // dostuff
        }

or is there some better way of doing it?

/M

From stackoverflow
  • Since you are doing it with MVC - you could make TimeRange1 a bool[].

    Then, you could always do this with linq

    var newItems = TimeRange1.Select(i => i == false);
    
    foreach(var item in newItems)
    {
     ....
    }
    

    or you could simplify it

    foreach(var item in TimeRange1.Select(i => i == false))
    {
     ....
    }
    
    molgan : how do I get: foreach(var item in TimeRange1.Select(i => i != "false")) to work? I cant seem to get hold of the value
    Daniel A. White : You can't `not` a string value. Remove the quotes.
    Daniel A. White : ...& change the type of `TimeRange1`.
  • Assuming TimeRange1 is your CheckBox[], try this:

    for (int i = 0; i < TimeRange1.Length; i++)
    {
        if (TimeRange1[i] == "on")
        {
           // dostuff
        }
    }
    
    Daniel A. White : This wont work - he is using MVC.

0 comments:

Post a Comment