gpt4 book ai didi

c# - 如何在列表和字典之间进行左连接?

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:24 25 4
gpt4 key购买 nike

我正在尝试将列表与字典相交,这非常有效:

    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);
}

enter image description here

但是,我想做一个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"}

如果交集不存在,我如何向交集添加默认值?

最佳答案

基于这个例子:Left join on two Lists and maintain one property from the right with Linq你也可以像这样用 GroupJoin 解决它:

public static IDictionary<string, string> GetValues(IReadOnlyList<string> keys, IHeaderDictionary headers, string defaultValue)
{
return keys.GroupJoin(headers, key => key, header => header.Key, (key, header) => new { key, header })
.SelectMany(x => x.header.DefaultIfEmpty(), (x, header) => new { x.key, header.Value })
.Select(x => new KeyValuePair<string, string>(x.key, x.Value))
.ToDictionary(p => p.Key, p => p.Value ?? defaultValue);
}

关于c# - 如何在列表和字典之间进行左连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54914373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com