Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Dictionary<A,B> + Dictionary<B,C> to create Dictionary<A,C>

Tags:

c#

dictionary

Any cool quick ways to take two dictionaries to create a third that maps the key of the first to the value of the second in an inner-join style?

Dictionary<A,B> dic1 = new Dictionary<A,B> {{a1,b1},{a2,b2},{a3,b3}};
Dictionary<B,C> dic2 = new Dictionary<B,C> {{b1,c1},{b2,c2},{b4,c4}};

Dictionary<A,C> dic3 = SomeFunction(dic1,dic2);
// dic3 = {{a1,c1},{a2,c2}}
like image 217
chillitom Avatar asked Dec 07 '25 04:12

chillitom


1 Answers

You could do something like this to join on the inner value

Dictionary<int, string> first = new Dictionary<int, string> { {1, "hello"}, {2, "world"}};

Dictionary<string, bool> second = 
    new Dictionary<string, bool> { { "hello", true }, {"world", false}};

var result = (from f in first
              join s in second on f.Value equals s.Key
              select new { f.Key, s.Value }).ToDictionary(x => x.Key, y => y.Value);

If you dump out result you'll see it is a Dictionary with the value {1: true, 2: false}

like image 85
Roly Avatar answered Dec 08 '25 16:12

Roly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!