Reputation: 41
I am searching for a construction to build a method in (C#) for construct a query URL based on Dictionary list. The solution I build didn't matched with the output I want. Does someone I better idea?
public string querystring()
{
//start with ?
var startPosition = string.Join("?", availiblebalance.FirstOrDefault().Key + "=" + availiblebalance.FirstOrDefault().Value);
//var removeElement = startPosition.Split('='); availiblebalance.Remove(removeElement[0]);
var otherPostions = string.Join("&", availiblebalance.Select(x => x.Key + "=" + x.Value).ToArray());
var result = string.Format("{0}{1}", startPosition,otherPostions);
return result;
}
Upvotes: 0
Views: 300
Reputation: 8792
There is an HttpUtility
that allows you to build the query string.
var queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
foreach (var entry in myDictionary)
queryString[entry.Key] = entry.Value;
return "?" + queryString.ToString();
Upvotes: 0
Reputation: 136239
Building a query string from a dictionary should be fairly straightforward - you dont need to treat the start position and the rest of the params separately.
var queryString = "?" + String.Join("&",
myDictionary.Select(kv => String.Concat(kv.Key,"=",kv.Value)));
You may need to UrlEncode
the values, depending on what they contain.
Upvotes: 2