-3

Say I have two dictionaries:

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");

How can I merge the two dictionaries so that the resulting dictionary updates the keys only where their corresponding values are empty? Additionally, the merge should not add any keys that are present in new but not in orig. That is, "one" still has the value "value one" while "two" and "three" are updated with the values from new.

I tried using orig.Concat(new);, but that leaves me with the original dictionary. Perhaps this can be done with LINQ?

4

4 回答 4

6

尝试:

orig = orig.Keys.ToDictionary(c => c, c=>(orig[c] == "" ? newDict[c] : orig[c]));
于 2013-10-09T14:56:07.753 回答
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
于 2013-10-09T15:06:05.470 回答
1

我会用foreach

foreach (var pair in orig.Where(x=> string.IsNullOrEmpty(x.Value)).ToArray())
{
    orig[pair.Key] = newone[pair.Key];
}
于 2013-10-09T15:04:27.073 回答
1

扩展方法“单行”在帮助澄清意图时非常有用,但对于这样的事情,我倾向于编写一个带有显式循环的小方法来执行所需的操作。我认为这比使用各种扩展方法转换创建新字典要干净得多:

    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;
        }
    }
于 2013-10-09T15:05:46.753 回答