linq C#求两个字典的交集并将键和两个值存储在列表中

0md85ypi  于 2023-01-18  发布在  C#
关注(0)|答案(2)|浏览(145)

我想交叉2个字典,但我不知道如何存储historicalHashtags[x],我设法只存储了1个字典的键和值。

var intersectedHashTags = currentHashTags.Keys.Intersect(historicalHashTags.Keys).
ToDictionary(x => x, x => currentHashTags[x]);

但是,我希望将结果存储在一个列表中,该列表包括Key、currentHashtags[x]和historicalHashtags[x]
示例:

Dictionary<string, int> currentHashTags = 
{ ["#hashtag1", 100], ["#hashtag2", 77], ["#hashtag3", 150], ...} 
Dictionary<string, int> historicalHashTags = 
{ ["#hashtag1", 144], ["#hashtag4", 66], ["#hashtag5", 150], ...} 

List<(string,int,int)> result = { ["#hashtag1", 100, 144] }
0s0u357o

0s0u357o1#

为了只保留两个字典共有的元素,可以在它们的键上使用Dictionary类型的Intersect方法,然后使用Select方法将结果转换为IEnumerable<(string, int, int)>,最后将其转换为列表。

Dictionary<string, int> currentHashTags = new()
{
    {"#hashtag1", 11},
    {"#hashtag2", 12},
    {"#hashtag3", 13},
    {"#hashtag4", 14}
};
Dictionary<string, int> historicalHashTags = new()
{
    {"#hashtag2", 22},
    {"#hashtag3", 23},
    {"#hashtag4", 24},
    {"#hashtag5", 25}
};

List<(string, int, int)> intersectedHashTags = currentHashTags.Keys
    .Intersect(historicalHashTags.Keys)
    .Select(key => (key, currentHashTags[key], historicalHashTags[key]))
    .ToList();
// Content of intersectedHashTags:
// ("#hashtag2", 12, 22)
// ("#hashtag3", 13, 23)
// ("#hashtag4", 14, 24)
x8goxv8g

x8goxv8g2#

假设您的字典类型为Dictionary<string, string>,并且您希望Dictionary<string, List<string>>作为输出,则如下所示:

Dictionary<string, List<string>> combinedHashTags =
    currentHashTags
        .Concat(historicalHashTags)
        .GroupBy(x => x.Key, x => x.Value)
        .ToDictionary(x => x.Key, x => x.ToList());

要获得交集,可以使用简单的连接:

List<(string Key, int current, int historical)> combined =
(
    from c in currentHashTags
    join h in historicalHashTags on c.Key equals h.Key
    select (c.Key, c.Value, h.Value)
).ToList();

相关问题