Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a FormCollection by keys that start with a certain string

Tags:

c#

asp.net-mvc

Is there a nice linqy way of splitting a FormCollection into a Dictionary<string,string> that contains only those keys that start with a certain string?

(This question is basically the same as this-> but for C#/FormCollection instead of python Slicing a dictionary by keys that start with a certain string)

Here's what I came up with to get around the problem:

public ActionResult Save(FormCollection formCollection) {
  var appSettings = new Dictionary<string, string>();
  var appKeys = formCollection.AllKeys.Where(k => k.StartsWith("AppSettings."));
  foreach (var key in appKeys)
  {
      appSettings[key] = formCollection[key];
  }
...

Edit: The problem with this code, is that I have to do it multiple times for different StartsWith strings, and will therefore need to create a 'utility' method to do the above. It would be nice if it could read in one line like:

formCollection.Where(k=>k.Key.StartsWith("AppSettings.");

Background (not necessary to solve the problem): The context is asp.net mvc, and of a form with a dynamic dictionary of fields.

It's also similar to this question - Return FormCollection items with Prefix - but not quite the same.

And having read this answer How to build C# object from a FormCollection with complex keys - I started to wonder whether I'd be better off not even using form post, but sending JSON instead.

like image 213
PandaWood Avatar asked Feb 03 '11 23:02

PandaWood


1 Answers

If you're looking for a "nice" way of taking an existing dictionary, producing a new dictionary with copies of keys+values, for a subset of the keys, some LINQ code will do this nicely:

var appSettings = formCollection.AllKeys
    .Where(k => k.StartsWith("AppSettings."))
    .ToDictionary(k => k, k => formCollection[k]);
like image 101
Lasse V. Karlsen Avatar answered Nov 11 '22 13:11

Lasse V. Karlsen