【问题标题】:intersect a dictionary and a list to return another dictionary将字典和列表相交以返回另一个字典
【发布时间】:2019-07-15 18:21:40
【问题描述】:

如何传入标头列表并取回键/值对?

我创建了如下方法:

public static IDictionary<string, string> GetHeaderValues(
    IReadOnlyList<string> keys, IHeaderDictionary headers)
{
}

我想传入一个字符串列表,例如"trackingId, requestId, corrId",然后取回这样的字典:

trackingId: 123123
requestId: abc123123
corrId: xyz123

这样做的目的是传递所有标头,并仅检索所需的标头。

我们如何将IReadOnlyListIHeaderDictionarymap这两个对象相交成一个普通的IDictionary

我尝试将两者与以下内容相交:

headers.Keys.Intersect(keys); 但是这将返回一个可枚举的字符串。

【问题讨论】:

  • 它们是在来自req的请求中传递的:public static async Task&lt;IActionResult&gt; Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
  • @HereticMonkey 我已经更新了。让我知道我可以提供哪些其他信息。
  • @HereticMonkey 请注意下面 Carlo 的回答。将来可能会对您有所帮助
  • 抱歉,这个答案将如何帮助我了解您之前尝试过的内容?

标签: c# .net asp.net-core functional-programming


【解决方案1】:

一个简短的伪代码

intersect(keys1,keys2)        // get common keys list
    |> map to (key,value)     // map to key-value pair list
    |> to dictionary           // convert list to dict

C# 实现:

public static IDictionary<string, string> GetHeaderValues(IReadOnlyList<string> keys, IHeaderDictionary headers)
{
    return keys.Intersect(headers.Keys)
        .Select(k => new KeyValuePair<string,string>(k,headers[k]))
        .ToDictionary(p => p.Key, p => p.Value);
}

测试用例:

var list = new List<string>{
    "Content-tyb3",  // non-exist
    "Cookie",        
    "Accept-Language",
    "Program",      // non-exist
};
var headers = GetHeaderValues(list,Request.Headers);

【讨论】:

    【解决方案2】:

    您可以将键与标头连接起来,然后将结果转换成字典,但值可能不是单个字符串。在这个解决方案中,我在 StringValue 对象上调用了 ToString(),这可能不是您想要的,但它是您的方法签名所显示的:

    public static IDictionary<string, string> GetHeaderValues(
        IReadOnlyList<string> keys, IHeaderDictionary headers)
    {
        return headers
        .Join(keys, h => h.Key, k => k, (h, k) => h)
        .ToDictionary(h => h.Key, h => h.Value.ToString());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多