Merge two dictionaries and remove duplicate keys and sort by the value
Asked Answered
S

7

5

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"}
Sarmentum answered 8/8, 2013 at 10:22 Comment(3)
Dictionary won't allow you to add duplicate keys by default.Bennett
What's your question?Mendelson
I have edited the question. Basically I want to merge dictionaries (without having duplicate entries) and if key not present in the first dictionary then add item from second dictionary to first dictionary.Sarmentum
S
6

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"}
Smaragdine answered 8/8, 2013 at 10:30 Comment(1)
Thanks for the response. This is only one line answer.Sarmentum
P
1

Try this:

foreach (var item in firstDict)
{
    secondDict[item.Key] = item.Value;
}

Update:

If you want to preserve initial values, make a copy of secondDict:

Dictionary<int, string> resultDict = new Dictionary<int, string>(secondDict);
foreach (var item in firstDict)
{
    resultDict[item.Key] = item.Value;
}
Pipsqueak answered 8/8, 2013 at 10:27 Comment(1)
The original post preserves the existing value.Apterous
S
1

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.

Satyr answered 8/8, 2013 at 10:27 Comment(0)
M
1
foreach (int key in secondDict.Keys)
{
    if (!firstDict.ContainsKey(key))
    firstDict.Add(key, secondDict[key]);
}
Maryannamaryanne answered 8/8, 2013 at 10:29 Comment(0)
P
1

I would try this:

foreach(var pair in secondDict)
{
   if(!(firstDict.ContainsKey(pair.Key)))
   {
      firstDict.Add(pair.Key, pair.Value);
   }
}

Is this what you want? I haven´t tested it yet by compiler, so give it a try.

Pryer answered 8/8, 2013 at 10:35 Comment(0)
L
0

I am not sure, do you want to merge both of them? If so, can you just:

1st. Create a copy of the firstDict where the final results will be set.

2nd. For each key in secondDict:

1. Check if key exists in firstDict.

1.1. If it does exist(we want to keep the current result): do not do anything(sorry I miss read the result earlier)

1.2. If it doesn't exist then insert it as is(key-value from secondDict into firstDict)

Hopefully it helps!

Lewie answered 8/8, 2013 at 10:27 Comment(0)
G
-1

I prefer to let C# do the work.

return firstDict.ToList().Union(SecondDict.ToList()).ToDictionary(x => x.Key, x => x.Value);

and if you can, change the return to IEnumerable, and remove ToDictioary.

return firstDict.ToList().Union(SecondDict.ToList());
Grovergroves answered 26/1 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.