Solved

Append Dictionary onto an existing one

Posted on 2010-09-08
5
830 Views
Last Modified: 2013-12-17
Hi,

I have an existing dictionary variable:

      Dictionary<string, string> itemList = new Dictionary<string, string> ();

And I would like to add the below one to it so the values are added to the end, its returned from a method.

       Dictionary<string, string> returnValue = new Dictionary<string, string> ();

ie somthing like:  itemList +=returnValue (I know this is wrong)

0
Comment
Question by:darren-w-
5 Comments
 
LVL 53

Accepted Solution

by:
Dhaest earned 300 total points
ID: 33626924
You can the concat

Dictionary<string, string> d3 = d1.Concat(d2).ToDictionary(e => e.Key, e => e.Value);
 
        foreach (var item in d3)
        {
            Console.WriteLine(item.Key);
        }
0
 
LVL 5

Assisted Solution

by:LlamaJoe
LlamaJoe earned 100 total points
ID: 33627063
using LINQ you can join into a new variable, and then assign it back to the original variable.

                    Dictionary<string, string> itemList = new Dictionary<string, string> ();
                    itemList.Add("a", "b");
                    Dictionary<string, string> returnValue = new Dictionary<string, string> ();
                    returnValue.Add("c", "d");

                    var newList = itemList.Concat(returnValue);

Dictionary is not a sealed class, so you could override the Add method to make a method to allow you to add another dictionary and return the result.
0
 
LVL 12

Assisted Solution

by:w00te
w00te earned 100 total points
ID: 33627200
From:
http://stackoverflow.com/questions/712927/how-to-add-2-dictionary-contents-without-looping-in-c

d1.Concat(d2).ToDictionary(x => x.Key, x => x.Value);

-w00te
0
 
LVL 12

Expert Comment

by:w00te
ID: 33627208
Actually mine's prety much the same as Dhaest, go for his.  Sorry about that :)
-w00te
0
 
LVL 13

Author Comment

by:darren-w-
ID: 33627609
Ok thanks all
0

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question