bob mason
bob mason

Reputation: 913

C# Intersect Two Dictionaries and Store The Key and The Two Values in a List

I want to intersect the 2 dictionaries, but I am not sure how to store historicalHashTags[x] too, I managed to store only the key and value of 1 dictionary.

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

But, I want the result to be stored in a list that includes Key, currentHashTags[x], and historicalHashTags[x]

Example:

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

Upvotes: 1

Views: 153

Answers (2)

Enigmativity
Enigmativity

Reputation: 117027

Assuming your dictionaries are of type Dictionary<string, string> and you want Dictionary<string, List<string>> as output, then this works:

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

To get the intersection a simple join would work:

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

Upvotes: 1

AoooR
AoooR

Reputation: 441

To keep only the elements common to both dictionaries, you can use the Intersect method of type Dictionary on their keys. Then with Select method you transform this result into an IEnumerable<(string, int, int)>. Finally convert it to a list.

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)

Upvotes: 4

Related Questions