1

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

2
  • What output do you expect? "one=1&two=2& … six=6"? Commented Jul 24, 2014 at 5:24
  • hi Marcel B : yes that's the output i needed Commented Jul 24, 2014 at 5:28

2 Answers 2

3

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());
Sign up to request clarification or add additional context in comments.

Comments

1
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.

2 Comments

i think that would get more "&"sign as string character which still need to remove or replace. Thanks
you’re right… Aggregate would place a & at the start, That’s not what I intended. I’m going to change that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.