0

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;
}
Jamiec
  • 128,537
  • 12
  • 134
  • 188
  • 1
    `The solution I build didn't matched with the output I want` - you might want to tell us what you *do* want! – Jamiec Jul 31 '17 at 16:02
  • Is this answer of any use? https://stackoverflow.com/questions/829080/how-to-build-a-query-string-for-a-url-in-c Or maybe this article http://www.java2s.com/Code/CSharp/Network/DictionaryToQueryString.htm –  Jul 31 '17 at 16:02
  • I suspect you're missing `HttpUtility.UrlEncode` – A.Akram Jul 31 '17 at 16:05

2 Answers2

2

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.

Martin Brown
  • 23,657
  • 13
  • 76
  • 113
Jamiec
  • 128,537
  • 12
  • 134
  • 188
0

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();
PiotrWolkowski
  • 7,942
  • 6
  • 43
  • 65