I'm attempting to intersect a list with a dictionary, which works perfectly:
public static IDictionary<string, string> GetValues(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);
}
The usage of the above method would be something like this:
[TestMethod]
public void GetValues_returns_dictionary_of_header_values()
{
var headers = new List<string> { { "trackingId" }, { "SourceParty" }, { "DestinationParty" } };
var trackingIdValue = "thisismytrackingid";
var sourcePartyValue = "thisismysourceparty";
var destinationPartyValue = "thisismydestinationparty";
var requestHeaders = new HeaderDictionary
{
{"trackingId", new Microsoft.Extensions.Primitives.StringValues(trackingIdValue) },
{"SourceParty", new Microsoft.Extensions.Primitives.StringValues(sourcePartyValue) },
{"DestinationParty", new Microsoft.Extensions.Primitives.StringValues(destinationPartyValue) },
{"randomHeader", new Microsoft.Extensions.Primitives.StringValues("dontcare") }
};
var headerValues = HeaderOperators.GetValues(headers, requestHeaders);
Assert.IsTrue(headerValues.ContainsKey("trackingId"));
Assert.IsTrue(headerValues.ContainsKey("SourceParty"));
Assert.IsTrue(headerValues.ContainsKey("DestinationParty"));
Assert.IsTrue(headerValues.Count == headers.Count);
}
However, rather than an intersect
I would like to do a left join
, where for example if I search the dictionary for a value that does not exist it would still return that key with some default value
.
For example, if we input oneMoreKey
:
var headers = new List<string> { { "trackingId" }, { "SourceParty" }, { "DestinationParty" }, {"oneMoreKey"} };
Then I would expect that the result of this would be something like this:
var headerValues = HeaderOperators.GetValues(headers, requestHeaders, "myDefaultValue");
Where headerValues
is:
{"trackingId", "thisismytrackingid"}
{"SourceParty", "thisismysourceparty"}
{"DestinationParty", "thisismydestinationparty"}
{"oneMoreKey", "myDefaultValue"}
How do I add a default value to the intersection if one does not exist?