【发布时间】:2016-10-22 17:45:11
【问题描述】:
背景
当我更新网格中的值时,我创建了两个有序字典(旧值和新值)。然后,我想比较哪些值不同,并对我的数据源(恰好是一个列表)进行更改。
代码
这是我创建的用于比较两个类型为 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;
}
问题
我似乎无法将字典的值转换为字符串,出现以下异常。
指定的转换无效。
在这条线上
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;
}
【问题讨论】:
标签: c# dictionary ordereddictionary