How do you pass in a list of headers and get back the key/value pairs?
I've created a method like the following:
public static IDictionary<string, string> GetHeaderValues(
IReadOnlyList<string> keys, IHeaderDictionary headers)
{
}
I'd like to pass in a list of string such as "trackingId, requestId, corrId"
and get back a dictionary like so:
trackingId: 123123
requestId: abc123123
corrId: xyz123
The purpose of this is to pass in ALL the headers, and retrieve only the desired headers.
How do we intersect these two objects IReadOnlyList
and IHeaderDictionary
and map
into a regular IDictionary
?
I've attempted to intersect the two with the following:
headers.Keys.Intersect(keys);
however this will return an ienumerable string.
a short pseudo-code :
intersect(keys1,keys2) // get common keys list
|> map to (key,value) // map to key-value pair list
|> to dictionary // convert list to dict
C# Implementation :
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);
}
Test Case :
var list = new List<string>{
"Content-tyb3", // non-exist
"Cookie",
"Accept-Language",
"Program", // non-exist
};
var headers = GetHeaderValues(list,Request.Headers);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments