Search code examples
c#dictionarycompareintersectexcept

Compare Keys in Two Dictionaries


I'm trying to compare two dictionaries, the program is written in C# Visual Studio 2010.

Dictionary<int, string> members1 = new Dictionaries<int, string>{
    {1, "adam"},
    {2, "bob"},
    {3, "cameron"}
}

Dictionary<int, string> members2 = new Dictionaries<int, string>{
    {1, "adam"},
    {2, "bill"},
    {4, "dave"}
}

I would like to find the same id (key), and it doesn't matter if the name (value) is the same or not.

I've been searching and found Intersect and Except, but I don't think it work quite the way I wanted it.

With the example above, if I call an Intersect function, I want it to return List<int>{1, 2}.

If I call something like members1.Except(members2), I want it to return

Dictionary<int, string> intersectMembers{
    {1, "adam"},
}

A solution I thought of doing is to write 2 for-loops and using dictionary.Contains(key) to get the result I want.

Is there a more straight forward way of doing this?

Thanks


Solution

  • If you want a "Common Dictionary" returned I believe you could do it this way:

       var intersectMembers =  members1.Keys.Intersect(members2.Keys)
                                      .ToDictionary(t => t, t => members1[t]);
    

    or, alternatively:

       var intersectMembers =  members1.Where(x => members2.ContainsKey(x.Key))
                                 .ToDictionary(x => x.Key, x => x.Value);
    

    However, if you want a "Common List" returned then Sergey is right and you can implement his answer.