tags:

views:

41

answers:

2

Hello

I have a asp.net mvc page with an array of checkboxes that gets posted to an insert-method.

And I have this string[] UsergroupIDs, that gets mapped properly, but it contatins "false"-values, and is in string[].

Is there some easy way of cast it to int[] and remove the "false"-values?

Using the .Select and .Where if possible? :)

/M

A: 

this is the safest way:

List<int> userGroupIDs;
foreach (var stringUserGroupID in stringUserGroupIDs)
{
    int userGroupID;
    if (!int.TryParse(stringUserGroupID, out userGroupID)
    {
        continue;
    }
    userGroupIDs.Add(userGroupID);
}

var myArray = userGroupIDs.ToArray();

but, as you need a variable-declaration, and i fear this can't be done with let, you need to use a foreach or for

not so safe way (filtering only false):

from stringUserGroupID in stringUserGroupIDs
where !string.Equals(stringUserGroupID, "false", StringComparison.CurrentCultureIgnoreCase)
select int.Parse(stringUserGroupID)

edit:
funny ...

var userGroupID = 0;
var userGroupIDs = stringUserGroupIDs.Where(stringUserGroupID => int.TryParse(stringUserGroupID, out userGroupID)).Select(stringUserGroupID => userGroupID);

no guarantee that this works ... :)

Andreas Niedermair
+3  A: 

First, filter the false values. Then parse them:

var intValues = stringValues.Where(x => x != "false").Select(x => int.Parse(x));
Konrad Rudolph