c#从字符串中的键值对中提取值

Mic*_*hel 12 .net c# string query-string

我有一个像这样的字符串:

blablablamorecontentblablabla?name=michel&score=5&age=28&iliedabouttheage=true
Run Code Online (Sandbox Code Playgroud)

看起来像常规查询字符串是,但我不在任何Web上下文中

现在我想通过他们的键提取值(在=符号之后),例如,名称(michel),分数(5),年龄(28)等.

通常我解析字符串就像获取单词'name'的字符串中的位置,然后将5添加到它(长度'name =')并将此位置命名为'start'然后搜索&-sign并命名该位置'结束',然后在位置开始和结束之间获取字符串.

但必须有一个更好的解决方案,这是一个正则表达式的事情吗?

Eri*_*lje 32

Try System.Web.HttpUtility.ParseQueryString, passing in everything after the question mark. You would need to use the System.Web assembly, but it shouldn't require a web context.


Luk*_*keH 15

If you want to create a dictionary of the key/value pairs then you could use a bit of LINQ:

Dictionary<string, string> yourDictionary =
    yourString.Split('?')[1]
              .Split('&')
              .Select(x => x.Split('='))
              .ToDictionary(y => y[0], y => y[1]);
Run Code Online (Sandbox Code Playgroud)

(You could skip the Split('?')[1] part if your string contained just the querystring rather than the entire URL.)