c# - 是否有处理嵌套字典的简单方法对象是字符串或另一个字典的类型?
问题描述
我正在创建一个应该能够将 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;
}
}
根据字典中传递的对象的类型,它应该在传递一个字符串时创建一个字符串,或者在传递另一个字典时调用自身。
提前感谢您的专业知识
解决方案
你可以通过创建一个扁平化嵌套字典的方法来使它更花哨:
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)));
推荐阅读
- c# - 在 Unity 中重新启动后 PlayerPrefs 未保存
- javascript - 如何防止多文档表单页面重新加载?
- python - 使用正则表达式进行 Python 分块
- c# - 从另一个脚本销毁游戏对象
- java - 将矩阵减少到每个单元格一个元素
- ios - 由 navigationController 呈现时未调用 ViewWill/DidAppear
- java - SpringDoc WebMvc 与 WebFlux
- mysql - 导入 50GB SQL 冻结或无法完成
- javascript - 如何使用 jQuery 从另一个网站下载文件?
- linux - 如何在没有换行符的情况下替换文件中的子字符串?