Gayan
Gayan

Reputation: 2860

Query String builder Error

I'm just trying to use dictionary data to build query string. i use this function.

public static string BuildQueryString(this IDictionary<string, string> source, bool withoutEmptyString)
    {
        return source != null ? String.Join("&", source.Keys
        .Where(key => !withoutEmptyString || source.Values.Any(value => !String.IsNullOrEmpty(value)))
        .SelectMany(key => source.Values
            .Where(value => !withoutEmptyString || !String.IsNullOrEmpty(value))
            .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), value != null ? HttpUtility.UrlEncode(value) : string.Empty)))
        .ToArray())
        : string.Empty;
    }

but when i send the data like this

      var dataDictionary = new Dictionary<string, string>
        {   {"one", "1"},
            {"two", "2"},
            {"three", "3"},
            {"four", "4"},
            {"five", "5"},
            {"six", "6"}
        };

i'm getting string like this

"one=1&one=2&one=3&one=4&one=5&one=6&two=1&two=2&two=3&two=4&two=5&two=6&three=1&three=2&three=3&three=4&three=5&three=6&four=1&four=2&four=3&four=4&four=5&four=6&five=1&five=2&five=3&five=4&five=5&five=6&six=1&six=2&six=3&six=4&six=5&six=6"

what is the wrong i did in the code

thanks

Upvotes: 1

Views: 66

Answers (2)

Marcel B
Marcel B

Reputation: 3664

return source != null ? string.Join("&", 
                                    source.Where(keyValuePair => withoutEmptyString && !string.IsNullOrEmpty(keyValuePair.Value))
                                          .Select(keyValuePair => string.Format("{0}={1}", keyValuePair.Key, keyValuePair.Value)))     
                      : string.Empty;

Please check if my where clause works for you.

Upvotes: 1

astian
astian

Reputation: 684

How about something simpler like:

var fromSource = source.Where(s => !string.IsNullOrEmpty(s.Value)).Select(s => s.Key + "=" +     s.Value);
        return string.Join("&", fromSource.ToArray());

Upvotes: 3

Related Questions