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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With