c# dictionaries intersect

前端 未结 4 459
北海茫月
北海茫月 2021-01-01 20:48

I have a question about Linq / Lambda and the following issue:

I have two dictionaries, primary and secondary... These two dictionaries are defined as Key=string, Va

相关标签:
4条回答
  • 2021-01-01 21:05

    Untested:

    resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys).ToDictionary(t => t.Key, primaryDict[t.Key]);
    
    0 讨论(0)
  • 2021-01-01 21:09

    You could do in this way:

    resultDict =  primaryDict.Keys.Intersect(secondaryDict.Keys)
                                  .ToDictionary(t => t, t => primaryDict[t]);
    

    or, alternatively:

    resultDict =  primaryDict.Where(x => secondaryDict.ContainsKey(x.Key))
                             .ToDictionary(x => x.Key, x => x.Value);
    

    the latter maybe is slightly more efficient because avoids the creation of a throw-away collection (the one generated by the Intersect method) and does not require a second access-by-key to primaryDict.

    EDIT (as per comment) :

    resultDict =  
    primaryDict.Where(x => secondaryDict.ContainsKey(x.Key))
               .ToDictionary(x => x.Key, x => x.Value + secondaryDict[x.Key]);
    
    0 讨论(0)
  • 2021-01-01 21:09

    You can still use primaryDict within your Linq statement since you are creating a new dictionary, which only gets assigned to your variable once it is created:

    resultDict = primaryDict.Keys
                            .Intersect(secondaryDict.Keys)
                            .ToDictionary(t => t, primaryDict[t]);
    
    0 讨论(0)
  • 2021-01-01 21:09

    If you want to select out an object with the "value" of both dictionaries, because that what you probably want, the you can try something like this. Assuming that the keys for both dictionaries are the same i.e. that map each together, like a GUID between two systems

    dictA.Keys.Intersect(dictB.Keys).Select(x => new MyMappingClass
    {
        dictAValue= dictA[x], dictBValue= dictB[x]
    })
    
    0 讨论(0)
提交回复
热议问题