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"}
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"}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With