为HashSet编写IEqualityComparator <tuple <t,int =“”>&gt;

时间:2017-06-30 14:39:00

标签: c#

我想写一个扩展到C#的标准HashSet来计算出现次数(我知道,使用dict。但我很好奇是否以及如何... :)。

所以我有:

public class CountingHashSet{
    public CountingHashSet(IEqualityComparer<T> comparator)
    {
        hashSet = new HashSet<Tuple<T, int>>(new EqualityAdapter<T>(comparator));
    }
}

我现在想为IEqualityComparator<T>接口编写一个Adapter,以便在HashSet中的元组的First元素T上使用提供的比较器。

我想出了类似的东西,编译器不允许:

public class EqualityAdapter<T> : IEqualityComparer<T> where T : Tuple<T, int>
{
    private IEqualityComparer<T> comparator;

    public EqualityAdapter(IEqualityComparer<T> comparator)
    {
        this.comparator = comparator;
    }

    public bool Equals(T x, T y)
    {
        return comparator.Equals(x.First, y.First);
    }

    public int GetHashCode(T obj)
    {
        return comparator.GetHashCode(obj.First);
    }
}

请帮忙。 :)

提前致谢!

1 个答案:

答案 0 :(得分:3)

你的仿制品都错了。 T不能是Tuple<T, int>。相反,您的比较器应该在Tuple<T, int>上,然后您不需要任何约束。

public class TupleFirstItemEqualityComparer<T> : IEqualityComparer<Tuple<T, int>> 
{
    private IEqualityComparer<T> comparator;

    public TupleFirstItemEqualityComparer(IEqualityComparer<T> comparator)
    {
        this.comparator = comparator;
    }

    public bool Equals(Tuple<T, int> x, Tuple<T, int> y)
    {
        return comparator.Equals(x.First, y.First);
    }

    public int GetHashCode(Tuple<T, int> obj)
    {
        return comparator.GetHashCode(obj.First);
    }
}