Join two dictionaries using a common key

前端 未结 4 1005
广开言路
广开言路 2021-02-09 23:28

I am trying to join two Dictionary collections together based on a common lookup value.

var idList = new Dictionary();
idList.Add(1, 1);
idList.A         


        
相关标签:
4条回答
  • 2021-02-09 23:45

    I apologize if I misinterpretted your question, but do you just want to retrieve the Values from list B only where list A has a KeyValuePair with the same Key?

    from lookup in lookupList
    where idList.Keys.Contains(lookup.Key)
    select lookup.Value;
    
    0 讨论(0)
  • 2021-02-09 23:53
    from id in idList.Keys
    where lookupList.ContainsKey(id)
    let value1 = idList[id]
    let value2 = lookupList[id]
    select new {id, value1, value2}
    

    Or, more classically

    from kvp1 in idList
    join kvp2 in lookupList on kvp1.Key equals kvp2.Key
    select new {key = kvp1.Key, value1 = kvp1.Value, value2 = kvp2.Value}
    

    The mistake in your query is one of scoping:

    from a in theAs
    join b in theBs on (leftside) equals (rightside)
    

    a is in scope in the leftside area. b is in scope in the rightside area.

    0 讨论(0)
  • 2021-02-09 23:53
            var q = from id in idList
                    join entry in lookupList
                      on id.Key equals entry.Key
                    select entry.Value;
    

    Your desired linq statement will look like that, ID and Entry needed to be switched around on the condition.

    0 讨论(0)
  • 2021-02-09 23:59

    What do you think of this ?

    var values = idList.Keys.Select(i => lookupList[i]);
    
    0 讨论(0)
提交回复
热议问题