一个像Python的collections.Counter库的C#库 - >在C#中获取两个字典对象之间的值的区别

Gam*_*iac 8 c# python

这就是我在C#中创建一个Dictionary的方法.

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

在Python中,如果你有这样的字典:

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})
Run Code Online (Sandbox Code Playgroud)

如您所见,Counter在比较字典对象时非常有用.

C#中是否有一个库,可以让我做类似的事情,或者我是否需要从头开始编写代码?

Ser*_*rvy 5

您可以将两个字典连接在一起,然后根据给定的操作创建一个新字典,只需几行代码:

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);
Run Code Online (Sandbox Code Playgroud)

您没有展示过包装字典并-为它们提供运算符的系统类,但是如果您愿意,可以轻松创建自己的类:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)