Combining dictionaries at a key level and then at a cost level

I have two type dictionaries

Dictionary<String, String> one = new Dictionary<string, string>
{
    { "A", "1" },
    { "B", "2" },
    { "C", "3" },
    { "D", "4" },
    { "E", "5" },
    { "F", "6" },
    { "G", "7" },
    { "H", "8" }
};

Dictionary<String, String> two = new Dictionary<string, string>
{
    { "A", "1" },
    { "B", "2" },
    { "C", "3" },
    { "E", "4" },
    { "F", "4" },
    { "I", "6" },
    { "J", "10" },
    { "K", "11" }
};

I need to combine two dictionaries at a key level, and then at a value level and add the resulting dictionary to a new dictionary three, the resulting dictionary should not have the same keys or the same values, in which case the resulting dictionary is like

Dictionary<String, String> three = new Dictionary<string, string>
{
    { "A", "1" },
    { "B", "2" },
    { "C", "3" },
    { "D", "4" },
    { "E", "5" },
    { "F", "6" },
    { "G", "7" },
    { "H", "8" },
    { "J", "10" },
    { "K", "11" }
};

Now i use as

  • Combine all keys in two dictionaries
  • Create a new dictionary with new keys
  • delete duplicate values ​​(same values)

EDIT : if both dictionaries have the same key pair, then I need to save a pair of key values ​​from the first dictionary.

Is there a way to do this using LINQ? thanks in advance

+3
4

, , /:

var dictionary = dictionary1.Concat(dictionary2)
                            .ToLookup(pair => pair.Key, pair => pair.Value)
                            .ToDictionary(x => x.Key, x => x.First());

, ( - ), , .

+2
var three = new Dictionary<string, string>();
foreach(var kvp in two.Concat(one))
  three[kvp.Key] = kvp.Value;

, , , ; .

EDIT. three:

var keysWithDuplicateValues = three.ToLookup(kvp => kvp.Value, kvp => kvp.Key)
                                   .SelectMany(group => group.Skip(1))
                                   .ToList();

foreach(var key in keysWithDuplicateValues)
   three.Remove(key);   

, , , .

+1

linq-only / . dict2, dict1:

var dict3 = dict2.Concat(dict1)
    .Aggregate(new Dictionary<string, string>(), (d, kvp) => {
        d[kvp.Key] = kvp.Value;
        return d;
    });
+1
class StringKeyValuePairEqualityComparer : IEqualityComparer<KeyValuePair<string, string>>
{
    public bool Equals(KeyValuePair<string, string> x, KeyValuePair<string, string> y)
    {
        return x.Key == y.Key;
    }

    public int GetHashCode(KeyValuePair<string, string> obj)
    {
        return obj.Key.GetHashCode();
    }
}

var three = Enumerable.Concat(one, two)
                .Distinct(new StringKeyValuePairEqualityComparer())
                .ToDictionary(p => p.Key, p => p.Value);

int count = three.Keys.Count; // 11
+1
source

Source: https://habr.com/ru/post/1763043/


All Articles