【发布时间】:2019-02-27 20:58:32
【问题描述】:
我正在尝试将列表与字典相交,效果很好:
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);
}
上述方法的用法是这样的:
[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);
}
但是,我想做一个left join,而不是intersect,例如,如果我在字典中搜索一个不存在的值,它仍然会返回带有一些默认值value的键。
例如,如果我们输入oneMoreKey:
var headers = new List<string> { { "trackingId" }, { "SourceParty" }, { "DestinationParty" }, {"oneMoreKey"} };
那么我希望这个结果会是这样的:
var headerValues = HeaderOperators.GetValues(headers, requestHeaders, "myDefaultValue");
headerValues 在哪里:
{"trackingId", "thisismytrackingid"}
{"SourceParty", "thisismysourceparty"}
{"DestinationParty", "thisismydestinationparty"}
{"oneMoreKey", "myDefaultValue"}
如果交集不存在,我如何添加默认值?
【问题讨论】:
-
如果您想从具有唯一值的多个其他列表创建一个列表,您可以使用
Union。您只需要提供一个相等比较器,并弄清楚如果值(对于同一个键)在 2 个源之间不同时该怎么办。
标签: c# .net dictionary functional-programming visual-studio-2017