在 C# 中解析字符串中的查询字符串的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1206548/
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
Most optimal way to parse querystring within a string in C#
提问by jpkeisala
I have a querystring alike value set in a plain string. I started to split string to get value out but I started to wonder that I can proabably write this in one line instead. Could you please advice if there is more optimal way to do this?
我在普通字符串中设置了一个类似查询字符串的值。我开始拆分字符串以获取值,但我开始怀疑我是否可以将其写在一行中。如果有更好的方法来做到这一点,您能否提出建议?
I am trying to read "123" and "abc" like in Request.QueryString but from normal string.
我试图在 Request.QueryString 中读取“123”和“abc”,但从普通字符串中读取。
protected void Page_Load(object sender, EventArgs e)
{
string qs = "id=123&xx=abc";
string[] urlInfo = qs.Split('&');
string id = urlInfo[urlInfo.Length - 2];
Response.Write(id.ToString());
}
采纳答案by Nelson Reis
You can do it this way:
你可以这样做:
using System.Collections.Specialized;
NameValueCollection query = HttpUtility.ParseQueryString(queryString);
Response.Write(query["id"]);
Hope it helps.
希望能帮助到你。
回答by RichardOD
Look at HttpUtility.ParseQueryString. Don't reinvent the wheel.
看看HttpUtility.ParseQueryString。不要重新发明轮子。
回答by inspite
RichardOD is on it with HttpUtility.ParseQueryStringbut don't forget to look at TryParse
.
RichardOD 与HttpUtility.ParseQueryString一起 使用,但不要忘记查看TryParse
.
You can TryParse int, DateTimes etc