1

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] }
bob mason
  • 677
  • 1
  • 6
  • 11

2 Answers2

4

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)

AoooR
  • 370
  • 1
  • 9
1

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();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Thank you, No, my Dictionary is Dictionary, i want the result to be List, where string is the intersected key that is a unique value, int is currentHashTags values and int is historicalHashTags values. – bob mason Jan 18 '23 at 07:58
  • @bobmason The type `List` doesn't exist, did you mean `List<(string, int, int)>`, so a list of tuples? If so, you lost properties of dictionaries (i.g. access elements in O(1) time) – AoooR Jan 18 '23 at 08:12
  • yes sorry, List<(string, int, int)> , there are no lost properties, as the string is the intersected key between the 2 dictionaries, and the other 2 ints are the 2 dictionaries values, and that's all that I need. – bob mason Jan 18 '23 at 08:25