9

这就是我在 C# 中创建字典的方式。

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

在 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})

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

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

4

2 回答 2

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);

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

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();
    }
}
于 2013-09-26T16:54:56.983 回答
2

没有这样的内置功能,但您可以使用一些 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 } }
于 2013-09-26T16:45:45.667 回答