Query String构建器错误

时间:2014-07-24 05:15:47

标签: asp.net linq

我只是想使用字典数据来构建查询字符串。我使用这个功能。

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;
    }

但是当我发送这样的数据时

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

我得到这样的字符串

"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"

我在代码中做了什么错误

感谢

2 个答案:

答案 0 :(得分:3)

如何更简单:

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

答案 1 :(得分: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;

请检查我的where子句是否适合您。