对象是字符串或另一个字典的类型?,c#,dictionary,object"/>

首页 > 解决方案 > 是否有处理嵌套字典的简单方法对象是字符串或另一个字典的类型?

问题描述

我正在创建一个应该能够将 Dictionary 作为参数的方法。

此方法准备一组参数作为 get/post 参数附加到 URI。问题是,当我调用 BuildQueryData(item) 时,出现错误:无法将 KeyValuePair 转换为 Dictionary。

    private string BuildQueryData(Dictionary<string, object> param)
    {
        if (param == null)
            return "";

        StringBuilder b = new StringBuilder();
        foreach (var item in param)
        {
            Dictionary<string, object> o;
            if (item.GetType() == "".GetType())
                b.Append(string.Format("&{0}={1}", item.Key, WebUtility.UrlEncode((string)item.Value)));
            else if (item.GetType() == new Dictionary<string, object>().GetType())
                b.Append(BuildQueryData(item));
        }


        try { return b.ToString().Substring(1); }
        catch (Exception e)
        {
            log.Error(e.Message);
            return e.Message;
        }
    }

根据字典中传递的对象的类型,它应该在传递一个字符串时创建一个字符串,或者在传递另一个字典时调用自身。

提前感谢您的专业知识

标签: c#dictionaryobject

解决方案


你可以通过创建一个扁平化嵌套字典的方法来使它更花哨:

private static IEnumerable<KeyValuePair<string, string>>
    Flatten(Dictionary<string, object> dictionary)
{
    if (dictionary == null) yield break;
    foreach (var entry in dictionary)
    {
        if (entry.Value is string s)
        {
            yield return new KeyValuePair<string, string>(entry.Key, s);
        }
        else if (entry.Value is Dictionary<string, object> innerDictionary)
        {
            foreach (var innerEntry in Flatten(innerDictionary))
            {
                yield return innerEntry;
            }
        }
        else if (entry.Value == null)
        {
            // Do nothing
        }
        else
        {
            throw new ArgumentException(nameof(dictionary));
        }
    }
}

...然后像这样使用它:

string queryData = String.Join("&", Flatten(myNestedDictionary)
    .Select(e => e.Key + "=" + WebUtility.UrlEncode(e.Value)));

推荐阅读