I wrote previously a post where I combine 2 Lists together here. Recently, I had the requirement to join 2 dictionaries together. I needed to build a DataTable and an NHibernate HQL query dynamically where the column headings could be different than the name of the actual database column name. To do this I created a dictionary like the below.
Dictionary<string, string> Selected = new Dictionary<string, string>()
The first string, the key, stored the actual database column name. Since database column names and the key in a dictionary must be unique, I was ok with this approach. Secondly, the value part of the dictionary contained the column name I needed to have in the DataTable.
The change where I needed to ultimately bind the 2 dictionaries was based on a decision not to pass the dictionary as a parameter. Initially, there was a transaction which resulted in numerous methods executing having an end result be a dictionary as previously defined. The change required that I modify the dictionary in 2 places and then return, in the end a single dictionary. Passing the dictionary as a parameter would have resulted in too many methods being changed which would ripple across the entire program.
The first was I decided to join, combine, merge the dictionaries together is as below.
Dictionary<string, string> Dictionary1 = new Dictionary<string, string>
{
{"dbColumnName", "DataTableColumnName"}
};
Dictionary<string, string> Dictionary2 = MethodReturnsDictionary();
Dictionary<string, string> Selected = new Dictionary<string, string>();
Selected = Dictionary1.Union(Dictionary2)
.ToDictionary(pair =>
pair.Key,
pair => pair.Value);
Looking at the above I thought, wow 7 lines of code to join or combine 2 dictionaries. There must be a better way. There is. The code list below shows code which achieves the same but with less.
Dictionary<string, string> Dictionary3 = new Dictionary<string, string>
{
{"dbColumnName", "DataTableColumnName"}
}.Union(MethodReturnsDictionary())
.ToDictionary(pair => pair.Key, pair => pair.Value);
It worked out just like I needed.