通过与某些字符串键启动一个切片的FormCollection [英] Slicing a FormCollection by keys that start with a certain string

查看:150
本文介绍了通过与某些字符串键启动一个切片的FormCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有拆分的FormCollection 词典℃的不错的 linqy 的途径;字符串,字符串> 只包含那些具有一定的字符串开始键?

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?

(这个问题是基本相同,这 - >但对于C#/的FormCollection而不是蟒蛇<一个href=\"http://stackoverflow.com/questions/4558983/slicing-a-dictionary-by-keys-that-start-with-a-certain-string\">Slicing与某些字符串开始一本词典的键)

(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];
  }
...

编辑:此code中的问题,是我必须多次做不同的StartsWith字符串,因此需要创建一个实用的方法做以上。
这将是很好,如果它可以像一行写着:

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.");

<强>背景(解决问题没有必要):的上下文是asp.net的MVC,并与字段的动态辞典的表单

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

这也是类似于这样的问题 - 返回的FormCollection项目与preFIX - 但不完全一样。

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

和看了这个答案<一个href=\"http://stackoverflow.com/questions/2845304/how-to-build-c-object-from-a-formcollection-with-complex-keys\">How从复杂的按键一的FormCollection打造C#对象 - 我开始怀疑我是否会更好,即使不使用表单提交,但发送JSON而不是

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.

推荐答案

如果你正在寻找采取现有的字典中好的方式,生产具有键+值的副本一个新的字典,为的一个子集钥匙,一些LINQ code将做到这一点很好:

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]);

这篇关于通过与某些字符串键启动一个切片的FormCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆