Merge two dictionaries and remove duplicate keys and sort by the value
c#, dictionary
Solution
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"}
Problem
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"} ```