您如何传入标头列表并取回键/值对?
我创建了一个如下所示的方法:
public static IDictionary<string, string> GetHeaderValues(
IReadOnlyList<string> keys, IHeaderDictionary headers)
{
}
我想传入一个字符串列表,例如"trackingId, requestId, corrId"
并取回一个像这样的字典:
trackingId: 123123
requestId: abc123123
corrId: xyz123
这样做的目的是传入所有标头,并仅检索所需的标头。
我们如何将这两个对象IReadOnlyList
andIHeaderDictionary
和 and相交map
成一个正则IDictionary
?
我试图将两者与以下内容相交:
headers.Keys.Intersect(keys);
但是这将返回一个可枚举的字符串。
一个简短的伪代码:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句