将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");
CCD_ 16函数可以将CCD_ 17作为输入。我想记录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>>
所以现在我的全部问题都来了。你认为如何解决这个问题?
使用Select
创建所需类型的KeyValuePair
:
Dictionary<string,string> dictionary = new Dictionary<string,string>();
// fill with values
List<KeyValuePair<string,object>> objList = dictionary.Select(x => new KeyValuePair<string,object>(x.Key, x.Value)).ToList();