var nums = Regex.Matches(input, @"\d+").Cast<Match>().Select(m => m.Value)
.ToList();
c# Form Collection Values to List of Int
-
04-04-2022 - |
Question
I have a Form Collection in my C# MVC4 application. In index[0]
of this collection there is a string that will always be formatted like "10=on&13=on&15=on"
; the only difference being the number of #=on
in the string.
I want to pull each of the numbers from this string and add them to a list of ints. What would be the simplest method of doing this? Is Regex required?
Solution 2
OTHER TIPS
What would be the simplest method of doing this?
I would use a custom model binder:
public class MyModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.RequestContext.HttpContext.Request.Params;
var keys =
from key in request.Keys.Cast<string>()
where request[key] == "on"
select key;
var onValues = new List<int>();
foreach (var key in keys)
{
int value;
if (int.TryParse(key, out value))
{
onValues.Add(value);
}
}
return onValues.ToArray();
}
}
and then a controller action like that:
public ActionResult SomeAction([ModelBinder(typeof(MyModelBinder))]int[] values)
{
return View();
}
Now you could simply send the following request to this controller action and the custom model binder will do the job:
/SomeAction?10=on&13=on&15=on
Is Regex required?
Nooooooooooooooooooooo.
The string in question looks like a query string so one approach would be to use System.Web.HttpUtility.ParseQueryString()
to get a NameValueCollection
from the string. Then enumerate the keys and parse them to get integers.
var collection = System.Web.HttpUtility.ParseQueryString("10=on&13=on&15=on");
foreach (var key in collection.Keys.Cast<string>())
{
int i;
if (int.TryParse(key, out i))
{
// add i to list of ints
}
}