![](/img/trans.png)
[英]Is there a way to get all the querystring name/value pairs into a collection?
[英]Best way to take all querystring pairs and init a dictionary
我想在我的查詢字符串中存儲所有鍵/值對:
www.example.com/?a=2&b=3&c=34
進入字典。 有沒有一種快速的方法來做這個而不必手動循環所有的項目?
試試HttpUtility.ParseQueryString()
。
它會為您提供鍵和值的NameValueCollection
。
獲取問號后面找到的字符串,將字符串拆分為“&”字符。 然后,對於要返回的每個字符串,再次在'='字符上拆分。
你甚至可以為它創建一個擴展方法。
public static class StringExtensions
{
public Dictionary<string, string> ExtractQueryStringValues( this string target )
{
string queryString = target.Split (target.IndexOf ('?') + 1);
string[] keyvaluePairs = queryString.Split ('&');
Dictionary<string, string> result = new Dictionary<string, string>();
foreach( string pair in keyvaluePairs )
{
var tmp = pair.Split ('=');
result.Add (tmp[0], tmp[1]);
}
return result;
}
}
這樣的事情。 請記住,它不安全,因為它不處理每個邊緣情況。 (例如,給出一個在第一個問號之后沒有任何內容的字符串等等),但它應該讓你開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.