C# 将查询字符串转换为 .Net 中的键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9669839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:23:42  来源:igfitidea点击:

Convert query string to key-value pair in .Net

c#asp.net.net

提问by Irwin

If I have a string like so:

如果我有这样的字符串:

"Name=Irwin&Home=Caribbean&Preference=Coffee"

is there a method in C# that can convert that to a key-value pair similar to Request.QueryString?

C# 中是否有一种方法可以将其转换为类似于 Request.QueryString 的键值对?

采纳答案by Brandon

You can try using HttpUtility.ParseQueryString.

您可以尝试使用HttpUtility.ParseQueryString.

var nvc = HttpUtility.ParseQueryString(yourString);

回答by PraveenVenu

回答by KeithS

You should be able to split this string based on the ampersands and equals signs, then feed each one into a new KeyValuePair:

您应该能够根据与符号和等号拆分此字符串,然后将每个字符串输入到一个新的 KeyValuePair 中:

Dictionary<string, string> myValues = new Dictionary<string,string>();

string[] elements = myString.Split('=','&');

for(int i=0;i<elements.Length; i+=2)
{
   myValues.Add(elements[i], elements[i+1]);
}

This is simplistic and makes a lot of assumptions about the format of your string, but it works for your example.

这很简单,并且对字符串的格式做了很多假设,但它适用于您的示例。

回答by xanatos

And now, for the longest LINQ expression...

现在,对于最长的 LINQ 表达式...

var dict = "Name=Irwin&Home=Caribbean&Preference=Coffee"
    .Split('&')
    .Select(p => p.Split('='))
    .ToDictionary(p => p[0], p => p.Length > 1 ? Uri.UnescapeDataString(p[1]) : null);

But be aware that it will throw if there are multiple keys with the same name.

但请注意,如果有多个同名的键,它会抛出。

If you want to protected yourself from this add:

如果您想保护自己免受此影响,请添加:

    .GroupBy(p => p[0]).Select(p => p.First())

just before the .ToDictionary(and after the .Select)

就在之前.ToDictionary(和之后.Select

this will take the first key=valueof the multiple ones. Change .First()to .Last()to take the last one.

这将取key=value多个中的第一个。更改.First().Last()取最后一个。

回答by Abbas

You can also use the ToDictionary() method:

您还可以使用 ToDictionary() 方法:

var input = "Name=Irwin&Home=Caribbean&Preference=Coffee";
var items = input.Split(new[] { '&' });
var dict = items.Select(item => item.Split(new[] {'='})).ToDictionary(pair => pair[0], pair => pair[1]);