user1512559
user1512559

Reputation:

How to merge 2 dictionaries

I have to aggregate two dictionaries.

Code:

private Dictionary <int, aor.PhysicalObject> agents;
private Dictionary <int, aor.PhysicalObject> objects;

agents = (from a in log
                   .InitialState
                   .Agents
                   .Agent 
         select a)
         .ToDictionary(d => Convert.ToInt32(d.id)
                       , d => d as aor.PhysicalObject);

objects = (from o in log
                     .InitialState
                     .Objects
                     .Object 
           select o)
           .ToDictionary(d => Convert.ToInt32(d.id)
                         , d => d as aor.PhysicalObject);

What I want now, is ONE dictionary containing all elements of the agents & objects dictionary.

You may think that there could be a problem with duplicate keys, but each key (id) is unique, so there will be no problem.

Would be very cool, if this task could be done via only one LINQ query.

Upvotes: 4

Views: 425

Answers (1)

A Coder
A Coder

Reputation: 3046

Provided the keys are unique you could combine the two dictionaries as follows:

//Code

private Dictionary <int, aor.PhysicalObject> merger;

merger = Enumerable
         .Concat(  from a in log
                             .InitialState
                             .Agents
                             .Agent
                    select a
                 ,  from o in log
                              .InitialState
                              .Objects
                              .Object  
                     select o
                ).ToDictionary(d => Convert.ToInt32(d.id)
                                ,  d => d as aor.PhysicalObject);

Upvotes: 1

Related Questions