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;
}
3
  • 1
    The solution I build didn't matched with the output I want - you might want to tell us what you do want! Commented Jul 31, 2017 at 16:02
  • Is this answer of any use? stackoverflow.com/questions/829080/… Or maybe this article java2s.com/Code/CSharp/Network/DictionaryToQueryString.htm Commented Jul 31, 2017 at 16:02
  • I suspect you're missing HttpUtility.UrlEncode Commented Jul 31, 2017 at 16:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.