如何加入两本词典?

时间:2017-01-01 20:05:10

标签: c# .net dictionary

我有两本词典。如果dict2中的值相同,那么我们必须从dict1添加匹配键的值,并在结果字典中生成结果,如下所示。

**dict1**                           **dict2**
Id         value                       Id          value
24379      348                         24379       270451
24368      348                         24368       270451
24377       90                         24377       270450
24366       90                         24366       270450
24369       10                         24369       270450   
24300       25

Result:
24379      696
24368      696
24377      190
24366      190
24369      190

我有以下逻辑,并希望优化此解决方案:

Dictionary<int, int> result = new Dictionary<int, int>();

foreach (int itemKey in dict1.keys)
{
    result.add (itemKey, dict1.Where(a => dict2.ContainsKey(a.key) 
                                       && dict2.ContiansKey(itemKey) 
                                       && dict2[a.key] == dict2[itemKey])
                              .Sum(a => a.value);
}

3 个答案:

答案 0 :(得分:2)

您可以分两步完成:

  • 准备字典以按dict2的值
  • 查找值
  • 浏览dict1,并从查找词典中插入值

以下是如何做到这一点:

var lookup = dict1
    .Where(p => dict2.ContainsKey(p.Key))
    .GroupBy(p => dict2[p.Key])
    .ToDictionary(g => g.Key, g => g.Sum(p => p.Value));
var res = dict1.Keys
        .Where(k => dict2.ContainsKey(k))
        .ToDictionary(k => k, k => lookup[dict2[k]]);

Demo.

答案 1 :(得分:1)

public static void DicAddTest()
{
    Dictionary<int, int> dic1 = new Dictionary<int, int>() { {24379,348}, { 24368, 348 }, { 24377, 90 }, { 24366, 90 } };
    Dictionary<int, int> dic2 = new Dictionary<int, int>() { { 24379, 270451 }, { 24368, 270451 }, { 24377, 270450 }, { 24366, 270450 } };
    Dictionary<int, int> dicResult = DicAdd(dic1, dic2);
    foreach (KeyValuePair<int, int> kvp in dicResult)
        Debug.WriteLine("{0} {1}", kvp.Key, kvp.Value);
    Debug.WriteLine("");
}
public static Dictionary<int, int> DicAdd(Dictionary<int, int> dic1, Dictionary<int, int> dic2)
{
    Dictionary<int, int> dicResult = new Dictionary<int, int>(dic1);
    foreach (int k in dic1.Keys.Where(x => dic2.Keys.Contains(x)))
        dicResult[k] = dicResult[k] + dicResult[k];
    return dicResult;
}

问题不明确

public static Dictionary<int, int> DicAdd2(Dictionary<int, int> dic1, Dictionary<int, int> dic2)
{
    Dictionary<int, int> dicResult = new Dictionary<int, int>();
    foreach (KeyValuePair<int, int> kvp in dic1.Where(x => dic2.Keys.Contains(x.Key)))
        dicResult.Add(kvp.Key, 2 * kvp.Value);
    return dicResult;
}

答案 2 :(得分:0)

如果您不确定dict1dict2是否具有相同的密钥,也许这样做会更容易:

var result = new Dictionary<int, int>();

foreach(var kvp in dict1)
{
    int value;

    if(dict2.TryGetValue(kvp.Key, out value))
    {
        result[kvp.Key] = kvp.Value * 2;
    }
}

这只会添加两个词典中的值。如果您的词典非常大,您可以使用Parallel For,或者考虑使用Hashtable代替。