3

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

Jon
  • 38,814
  • 81
  • 233
  • 382

2 Answers2

6

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
  • 28,023
  • 6
  • 71
  • 62
0

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.

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121