dictionary diff

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		Dictionary<string, object> d1 = new Dictionary<string, object> {
			{ "d1", "d1" },
			{ "d2", "x" } // This is the only difference
		};
		
		Dictionary<string, object> d2 = new Dictionary<string, object> {
			{ "d1", "d1" },
			{ "d2", "d2" }
		};
		
		GetDifferent(d1, d2).ForEach(d => {
			Console.WriteLine(d);
		});
	}
	
	private static List<string> GetDifferent(Dictionary<string, object> currentValues, Dictionary<string, object> previousValues)
	{
		var changed = currentValues
			          .Where(k => previousValues.Any(p => p.Key == k.Key && !AreValueEquals(k.Value, p.Value)))
			          .Select(k => k.Key);
		return changed.ToList();
	}
	
	private static object GetIfExists(Dictionary<string, object> values, string fieldName)
	{
		return values.ContainsKey(fieldName) ? values[fieldName] : null;
	}
	
	private static bool AreValueEquals(object o1, object o2)
    {
        return (o1 != null && o1.GetType().IsValueType)
            ? o1.Equals(o2)
            : o1 == o2;
    }
}
;