【发布时间】:2020-09-28 11:08:03
【问题描述】:
将List<KeyValuePair<string, string>> 转换为List<KeyValuePair<string, object>> 的最佳方法是什么?
正是我有Dictionary<string, string>,当我使用ToList() 函数时,它转换为List<KeyValuePair<string, string>>,但我想要 List<KeyValuePair<string, object>>。如何做到这一点?此外,我希望它到位,而不是使用循环或任何其他不必要的代码行。谢谢
真实场景:
有一个 Web API 项目,在请求的端点之一 Body 是 JsonElement 类型。要解析请求的Body,我这样做:
public JsonResult GetSomething([FromBody] JsonElement query){
string rawJson = query.ToString();
var keyValues = ParseRequestBodyHelper<Dictionary<string, string>>.ParseRequestBody(rawJson, "KeyValues");
}
ParseRequestBodyHelper 获取类型 (Dictionary<string, string>) 以反序列化与文件名 KeyValues 有关的对象。现在keyValues 是Dictionary<string, string>。
反序列化后,我想记录收到的信息。我的Logger 得到一个 KeyValuePairs 列表,如下所示:
Logger.Instance.GetLogger().Information("Body of request parsed");
GetLogger 函数可以将List<KeyValuePair<string, object>> 作为输入。我想记录 keyValues 以及类似以下的其他信息:
Logger.Instance.GetLogger(new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("Ip", IP),
new KeyValuePair<string, object>("Methodname", "GetSomething"),
})
.Information("Body of request parsed");
如果我这样做
Logger.Instance.GetLogger(new List<KeyValuePair<string, object>>(keyValues.ToList())
{
new KeyValuePair<string, object>("Ip", IP),
new KeyValuePair<string, object>("Methodname", "GetSomething"),
})
.Information("Body of request parsed");
它给了我一个错误,因为 keyValues.ToList() 类型是 List<KeyValuePair<string, string>> 但我想要 List<KeyValuePair<string, object>>。
所以现在我的整个问题都在这里。您认为如何解决这个问题?
【问题讨论】:
-
字典不是列表。您不需要将 Dictionary 转换为 List,因为 Dictionary 已经是 Enumerable。
-
因为字符串 is 对象,我真的不明白为什么要这样做。也不将字典转换为
KeyValuePairs的列表。你的目标是什么? -
为什么首先需要kvp列表?我无法想象为什么需要这种转换,也许您可以在这里提供您想要实现的目标。
标签: c# list dictionary key-value