c# - 如何在列表和字典之间进行左连接?
问题描述
我正在尝试将列表与字典相交,效果很好:
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);
}
但是,而不是intersect
我想做的left join
,例如,如果我在字典中搜索一个不存在的值,它仍然会返回带有一些默认值的键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"}
如果交叉点不存在,如何向交叉点添加默认值?
解决方案
您可以在创建新字典时使用 TryGetValue 以使用默认值填充它。
public static IDictionary<string, string> GetValues(IReadOnlyList<string> keys, IHeaderDictionary headers, string defaultValue)
{
return keys.ToDictionary(k => k, k => headers.TryGetValue(k, out string val) ? val : defaultValue);
}
推荐阅读
- python-3.x - 根据 np.select 条件生成增量权重的函数
- java - 如何在一个 java 类中实现两种布局?
- sql - Oracle Sql Developer - 使用 LISTAGG 函数时不会导出查询结果
- html - 一个 `display: flex` 的 `button` 不占用容器的全宽
- javascript - !function 语句在 javascript 中的作用是什么?
- javascript - 对数组执行计算操作和显示输出的难度
- node.js - 拒绝(TypeError):无法读取 null 的属性“名称”
- flutter - onBackgroundMessage 在颤动中不起作用
- ios - MPMediaItemPropertyLyrics 返回