You can join two dictionaries together, and then create a new one based on this operation with only a few lines of code:
Dictionary<string, int> d1 = new Dictionary<string, int>(); Dictionary<string, int> d2 = new Dictionary<string, int>(); var difference = d1.Join(d2, pair => pair.Key, pair => pair.Key, (a, b) => new { Key = a.Key, Value = a.Value - b.Value, }) .Where(pair => pair.Value > 0) .ToDictionary(pair => pair.Key, pair => pair.Value);
There is no system class that, as you have shown, wraps the dictionary a, provides an operator for them, but you can make your own if you want, quite easily:
public class Counter<T> : IEnumerable<KeyValuePair<T, int>> { private IEnumerable<KeyValuePair<T, int>> sequence; public Counter(IEnumerable<KeyValuePair<T, int>> sequence) { this.sequence = sequence; } public static Counter<T> operator -(Counter<T> first, Counter<T> second) { return new Counter<T>(first.Join(second , pair => pair.Key, pair => pair.Key, (a, b) => new KeyValuePair<T, int>(a.Key, a.Value - b.Value)) .Where(pair => pair.Value > 0)); } public IEnumerator<KeyValuePair<T, int>> GetEnumerator() { return sequence.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
Servy
source share