Search code examples
c#listlinqdictionaryintersect

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

Solution

  • 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)