【问题标题】:Convert List<KeyValuePair<string, string>> to List<KeyValuePair<string, object>> [closed]将 List<KeyValuePair<string, string>> 转换为 List<KeyValuePair<string, object>> [关闭]
【发布时间】:2020-09-28 11:08:03
【问题描述】:

将List&lt;KeyValuePair&lt;string, string&gt;&gt; 转换为List&lt;KeyValuePair&lt;string, object&gt;&gt; 的最佳方法是什么?
正是我有Dictionary&lt;string, string&gt;,当我使用ToList() 函数时,它转换为List&lt;KeyValuePair&lt;string, string&gt;&gt;,但我想要 List&lt;KeyValuePair&lt;string, object&gt;&gt;。如何做到这一点?此外,我希望它到位,而不是使用循环或任何其他不必要的代码行。谢谢


真实场景:
有一个 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&lt;string, string&gt;) 以反序列化与文件名 KeyValues 有关的对象。现在keyValues 是Dictionary&lt;string, string&gt;。
反序列化后,我想记录收到的信息。我的Logger 得到一个 KeyValuePairs 列表,如下所示:

Logger.Instance.GetLogger().Information("Body of request parsed");

GetLogger 函数可以将List&lt;KeyValuePair&lt;string, object&gt;&gt; 作为输入。我想记录 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&lt;KeyValuePair&lt;string, string&gt;&gt; 但我想要 List&lt;KeyValuePair&lt;string, object&gt;&gt;。

所以现在我的整个问题都在这里。您认为如何解决这个问题?

【问题讨论】:

  • 字典不是列表。您不需要将 Dictionary 转换为 List,因为 Dictionary 已经是 Enumerable。
  • 因为字符串 is 对象,我真的不明白为什么要这样做。也不将字典转换为KeyValuePairs 的列表。你的目标是什么?
  • 为什么首先需要kvp列表?我无法想象为什么需要这种转换,也许您可​​以在这里提供您想要实现的目标。

标签: c# list dictionary key-value


【解决方案1】:

使用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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-22
    • 2019-09-17
    • 2017-05-21
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多