比较两个有序字典

Compare Two Ordered Dictionaries

背景

我在更新网格中的值时创建了两个有序字典(旧值和新值)。然后我想比较哪些值不同并对我的数据源进行更改,该数据源恰好是一个列表。

代码

这是我创建的用于比较两个类型为 Dictionary<string,T>

的词典的方法
private Dictionary<string, string> FindChangedValues(OrderedDictionary newValues, OrderedDictionary oldValues)
{
    Dictionary<string, string> _dictKPVtoUpdate = new Dictionary<string, string>();

    foreach (KeyValuePair<string, string> newItem in newValues)
    {
        foreach (KeyValuePair<string, string> oldItem in oldValues)
        {
            if (newItem.Key == oldItem.Key)
            {
                if (!newItem.Value.ToString().Equals(oldItem.Value.ToString(), StringComparison.InvariantCultureIgnoreCase))
                {
                    _dictKPVtoUpdate.Add(oldItem.Key, newItem.Value);

                }
            }
        }
    }

    return _dictKPVtoUpdate;
}

问题

我似乎无法将字典的值转换为字符串,出现以下异常。

Specified cast is not valid.

这条线

foreach (KeyValuePair<string, string> newItem in newValues)

问题

是否有更好的方法来获取两个有序词典之间的变化?

如何将每个值都转换为字符串以便进行比较,或者有没有一种方法可以直接比较而不进行转换?

编辑:

回答

我使用的是 KeyValuePair 而不是所指出的 DictionaryEntry

将代码更改为以下,问题已解决。

更改代码

private Dictionary<string, string> FindChangedValues(OrderedDictionary newValues, OrderedDictionary oldValues)
{
    Dictionary<string, string> _dictKPVtoUpdate = new Dictionary<string, string>();

    foreach (DictionaryEntry newItem in newValues)
    {
        foreach (DictionaryEntry oldItem in oldValues)
        {

            if (newItem.Key.ToString() == oldItem.Key.ToString())
            {
                if (!newItem.Value.ToString().Equals(oldItem.Value.ToString(), StringComparison.InvariantCultureIgnoreCase))
                {
                    _dictKPVtoUpdate.Add(oldItem.Key.ToString(), newItem.Value.ToString());

                }
            }
        }
    }

    return _dictKPVtoUpdate;
}

DictionaryEntry 用于 OrderedDictionary 而不是 KeyValuePair。转换为 DictionaryEntry 并使用其 Key/Value 属性。

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be null, but a value can be.

OrderedDictionary/Remarks

迭代字典效率低下。 我会利用字典哈希并像这样实现它:

            Dictionary<string, string> _dictKPVtoUpdate = new Dictionary<string, string>();
        OrderedDictionary newValues =new OrderedDictionary();
        OrderedDictionary oldValues = new OrderedDictionary();

        foreach (DictionaryEntry tmpEntry in newValues)
        {
            if (oldValues.Contains(tmpEntry.Key))
            {
                _dictKPVtoUpdate.Add(tmpEntry.Key.ToString(),tmpEntry.Value.ToString());
            }
        }