Concat两个词典,以便更新原始的共享密钥

时间:2013-10-09 14:52:10

标签: c#

说我有两个词典:

Dictionary<string, string> orig = new Dictionary <string, string>();
orig.Add("one", "value one");
orig.Add("two", "");
orig.Add("three", "");

Dictionary<string, string> newDict = new Dictionary <string, string>();
newDict.Add("one", "this value should not be added");
newDict.Add("two", "value two");
newDict.Add("three", "value three");

如何合并两个词典,以便生成的词典仅在相应值为空的情况下更新键?此外,合并不应添加new中存在但orig中不存在的任何键。也就是说,“one”仍具有值“value one”,而“two”和“three”则使用new中的值进行更新。

我尝试使用orig.Concat(new);,但这留给我原始词典。也许这可以用LINQ来完成?

4 个答案:

答案 0 :(得分:6)

尝试:

orig = orig.Keys.ToDictionary(c => c, c=>(orig[c] == "" ? newDict[c] : orig[c]));

答案 1 :(得分:2)

这个循环可以实现您想要的高效和可读性:

Dictionary<string, string> result = new Dictionary<string, string>();
foreach (var keyVal in orig)
{
    if (!string.IsNullOrEmpty(keyVal.Value))
        result.Add(keyVal.Key, keyVal.Value);
    else
    {
        string val2;
        if (newDict.TryGetValue(keyVal.Key, out val2))
            result.Add(keyVal.Key, val2);
        else
            result.Add(keyVal.Key, "");
    }
}

结果:

one, value one  
two, value two
three, value three

答案 2 :(得分:1)

我会使用foreach

foreach (var pair in orig.Where(x=> string.IsNullOrEmpty(x.Value)).ToArray())
{
    orig[pair.Key] = newone[pair.Key];
}

答案 3 :(得分:1)

扩展方法'one-liners'在它们有助于澄清意图时非常好,但是对于这样的事情,我倾向于用一个带有显式循环的小方法来完成所需的操作。我认为这比使用各种扩展方法转换创建新词典要清晰得多:

    public void PopulateMissingValues(Dictionary<string, string> orig, Dictionary<string, string> newDict)
    {
        foreach (var pair in orig.Where(p => p.Value == string.Empty))
        {
            string newValue;
            if (newDict.TryGetValue(pair.Key, out newValue))
                orig[pair.Key] = newValue;
        }
    }