tags:

views:

152

answers:

2

How can return a subset of a FormCollection with key/values in tact for those items with a certain prefix? I can do it for keys only but I need the keys and values.

Thanks

A: 

Assume "form" is your FormCollection, I'd try to use Linq to do something like:


FormCollection subset = form.Where(x => x.Key.Contains("YourPrefix_"));

I didn't test that :)

Also, you may want to change .Contains() to be .Substring(0,11) == "YourPrefix_", depending on how your keys are named, etc.

mgroves
FormCollection does not contain a Where method
Jon
form.AsQueryable().Where(....) maybe? Also, you'll need to have a "using System.Linq;" statement
mgroves
Tried that but no luck
Jon
+3  A: 

Try this (tested):

var form = Request.Form;

var prefix = "prefix";

var asDictionary = form.Cast<string>()
    .Where(key => key.StartsWith(prefix))
    .ToDictionary(key => key, key => form[key])
    .ToList();
eu-ge-ne
Thanks! Seems a lot of work to do something reasonable straight forward.
Jon