首页 > 解决方案 > 如何在列表和字典之间进行左连接?

问题描述

我正在尝试将列表与字典相交,效果很好:

    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"}

如果交叉点不存在,如何向交叉点添加默认值?

标签: c#.netdictionaryfunctional-programmingvisual-studio-2017

解决方案


您可以在创建新字典时使用 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);
}

推荐阅读