Cutting a form using keys starting with a specific line

Is there a good way to split a FormCollection into a Dictionary<string,string> containing only those keys that start with a specific string?

(This question is basically the same as this->, but for C # / FormCollection instead of python Slicing a dictionary with keys starting with a specific line )

Here is what I found 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 this several times for different StartsWith lines, and therefore I need to create a "utility" method. It would be nice if he could read on one line, for example:

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

Background (not necessary to solve the problem): Context is asp.net mvc and forms with a dynamic dictionary of fields.

It also looks like this question - Returns FormCollection elements with a prefix - but not exactly the same.

And after reading this answer How to create a C # object from FormCollection with complex keys - I began to wonder if it would be better for me to even use the form message, but instead it sends JSON.

+7
source share
2 answers

If you are looking for a “good” way to use an existing dictionary by creating a new dictionary with copies of keys + values, for a subset of keys, some LINQ code will do it nicely:

 var appSettings = formCollection.AllKeys .Where(k => k.StartsWith("AppSettings.")) .ToDictionary(k => k, k => formCollection[k]); 
+14
source
 [HttpPost] public ActionResult Index(FormCollection collection) { Dictionary<string,object> form = new Dictionary<string, object>(); collection.CopyTo(form); return View(); } 
-6
source

All Articles