Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two dictionaries and remove duplicate keys and sort by the value

Tags:

c#

dictionary

I have to merge two dictionaries into one dictionary with removing duplicate entries and add if not present in the first dictionary.

 Dictionary<int, string> firstDict = new Dictionary<int, string>();
 firstDict.Add(1, "X");
 firstDict.Add(2, "B");

 Dictionary<int, string> secondDict = new Dictionary<int, string>();
 secondDict.Add(1, "M");
 secondDict.Add(4, "A");

Result Should be like this:

{4, "A"}
{2, "B"}
{1, "X"}
like image 938
Akshay Deshpande Avatar asked Aug 08 '13 10:08

Akshay Deshpande


2 Answers

You can use Concat with sample LINQ to achieve what you want. Here it is:

Dictionary<int, string> result = 
   firstDict.Concat(secondDict.Where(kvp => !firstDict.ContainsKey(kvp.Key)))
            .OrderBy(c=>c.Value)
            .ToDictionary(c => c.Key, c => c.Value);

The result is:

{4, "A"}
{2, "B"}
{1, "X"}
like image 175
Farhad Jabiyev Avatar answered Nov 02 '22 11:11

Farhad Jabiyev


You would do something like this:

var result = firstDict;
foreach(var newitem in secondDict.Where(x => !firstDict.ContainsKey(x.Key)))
    result.Add(newItem);

var sortedResult = result.OrderBy(x => x.Value);

Please note that result is still a dictionary but unsorted while sortedResult is sorted but no longer a dictionary, because the order of items in a dictionary is undefined. You can't use SortedDictionary<TKey, TValue> either, because it is sorted by the key and not the value.

like image 39
Daniel Hilgarth Avatar answered Nov 02 '22 13:11

Daniel Hilgarth