創建一個類來包含的區別:
public class DictionaryDifference<TKey, TValue>
{
public TKey Key
{
get;
set;
}
public TValue OriginalValue
{
get;
set;
}
public TValue NewValue
{
get;
set;
}
}
創建一個擴展方法,找到差異:
public static class DictionaryExtensions
{
public static IEnumerable<DictionaryDifference<TKey, TValue>> GetDifferencesFrom<TKey, TValue>(
this IDictionary<TKey, TValue> original,
IDictionary<TKey, TValue> latest)
where TValue : IComparable
{
foreach (var originalItem in original)
{
if (latest.ContainsKey(originalItem.Key))
{
if (originalItem.Value.CompareTo(latest[originalItem.Key]) != 0)
{
// The key is in the latest but the value is different.
yield return new DictionaryDifference<TKey, TValue>
{
Key = originalItem.Key,
OriginalValue = originalItem.Value,
NewValue = latest[originalItem.Key]
};
}
}
else
{
// The key is not in the latest dictionary.
yield return new DictionaryDifference<TKey, TValue>
{
Key = originalItem.Key,
OriginalValue = originalItem.Value,
NewValue = default(TValue)
};
}
}
foreach (var newItem in latest)
{
if (!original.ContainsKey(newItem.Key))
{
// The key is not in the original dictionary.
yield return new DictionaryDifference<TKey, TValue>
{
Key = newItem.Key,
OriginalValue = default(TValue),
NewValue = latest[newItem.Key]
};
}
}
}
}
創建2個字典和比較:
var dictionary1 = new Dictionary<int, double>();
dictionary1.Add(1, 40000);
dictionary1.Add(2, 56000);
dictionary1.Add(3, 77000);
dictionary1.Add(4, 80000);
dictionary1.Add(5, 100000);
var dictionary2 = new Dictionary<int, double>();
dictionary2.Add(1, 40000);
dictionary2.Add(2, 56000);
dictionary2.Add(3, 77000);
dictionary2.Add(4, 50000);
dictionary2.Add(6, 35000);
foreach (var difference in dictionary1.GetDifferencesFrom(dictionary2))
{
Console.WriteLine(
"Key {0} was {1} but is now {2}",
difference.Key.ToString(),
difference.OriginalValue.ToString(),
difference.NewValue.ToString());
}
OUTPUT:
Key 4 was 80000 but is now 50000
Key 5 was 100000 but is now 0
Key 6 was 0 but is now 35000
,只是'AB
'不'(AB)U(BA)'對嗎? – naveen 2012-02-17 10:19:30
@naveen,你是對的,但是這個'OHEMDictionary = employeeService.GetAllEmployees'讓我認爲OHEMDictionary包含所有員工。 – 2012-02-17 10:23:47
+1:是的,這是真的。我沒有正確閱讀。那會做。 – naveen 2012-02-17 10:32:58