A library similar to the Python collection. Counter Library for C # & # 8594; Getting the difference between values ​​between two dictionary objects in C #

This is how I would create a dictionary in C #.

Dictionary<string, int> d = new Dictionary<string, int>() { {"cheese", 2}, {"cakes", 1}, {"milk", 0}, {"humans", -1} // This one for laughs }; 

In Python, if you have a dictionary like this:

 from collections import Counter my_first_dict = { "cheese": 1, "cakes": 2, "milk": 3, } my_second_dict = { "cheese": 0, "cakes": 1, "milk": 4, } print Counter(my_first_dict) - Counter(my_second_dict) >>> Counter({'cheese': 1, 'cakes': 1}) 

As you can see, Counter very useful when comparing dictionary objects.

Is there a library in C # that will allow me to do something like this, or do I need to encode it from scratch?

+8
python c #
source share
2 answers

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(); } } 
+4
source share

There are no built-in functions, but you can use a little Linq:

 Dictionary<string, int> first = new Dictionary<string, int>() { {"cheese", 1}, {"cakes", 2}, {"milk", 3}, }; Dictionary<string, int> second = new Dictionary<string, int>() { {"cheese", 0}, {"cakes", 1}, {"milk", 4}, }; var results = (from x in first join y in second on x.Key equals y.Key where x.Value - y.Value > 0 select new { x.Key, Value = x.Value - y.Value }) .ToDictionary(p => p.Key, p => p.Value); // returns a dictionary like { { "cheese", 1 }, { "cakes", 1 } } 
+2
source share

All Articles