c# - SortedSet<T> 需要使用不同的排序和相等标准

标签 c# asp.net sortedset

我有一个以前在 HashSet 中使用的类。现在已经对此进行了更改,以便该类现在在 SortedSet 中使用,但相等测试不再像以前那样工作。我相信它使用 CompareTo 函数进行排序和比较,这是设计使然。

除了执行我自己的重复检查之外,还有人有任何想法吗?

public sealed class DatedID : IEquatable<DatedID>, IComparable
{
    readonly DateTime _added;
    readonly int _ID;

    public DateTime Added
    {
        get { return _added; }
    }

    public int ID
    {
        get { return _ID; }
    }

    public DatedID(int id)
        : this(id, DateTime.Now) {}

    public DatedID(int id, DateTime added)
    {
        id.ThrowDefault("id");
        added.ThrowDefault("added");

        _ID = id;
        _added = added;
    }

    // Compare

    int IComparable.CompareTo(object obj)
    {
        var other = (DatedID)obj;

        // Newest => oldest
        return this.Added > other.Added ? -1 : this.Added < other.Added ? 1 : 0;
    }

    // Equals

    public bool Equals(DatedID other)
    {
        if (other == null) return false;

        return this.ID == other.ID;
    }

    public override bool Equals(object obj)
    {
        if (obj == null) return false;

        var di = obj as DatedID;

        return di == null ? false : Equals(di);
    }

    public override int GetHashCode()
    {
        return ID.GetHashCode();
    }
}

最佳答案

如果您的意思是需要能够处理具有不同 ID 但相同 DateTime 的多个值,您可以将其包含在您的 CompareTo 实现中:

// TODO: Implement IComparable<DatedID> as well :)
int IComparable.CompareTo(object obj)
{
    var other = (DatedID)obj;
    int dateComparison = other.Added.CompareTo(this.Added);
    return dateComparison != 0
        ? dateComparison
        : _ID.CompareTo(other._ID);
}

如果您的意思是您不希望能够添加具有相同 ID 但不同日期的多个值,那么您无法使用 SortedSet 实现这一点。在 SortedSet 中,唯一的相等性衡量标准是比较是否返回 0。

关于c# - SortedSet<T> 需要使用不同的排序和相等标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28071629/

相关文章:

c# - 如何在 WebApi OwinHost Startup 中使用 Ninject bootstrapper?

c# - 为什么 Boolean 不抛出 StackOverflowException?

asp.net - 将ASP.NET的 "ReturnURL"转为绝对URL

c# - TweetSharp 在哪里?

c# - 如何替换字节

asp.net - web.config 位置元素设置

c# - 在非异步方法中调用异步并记录异步等待方法的异常

hash - 如何根据redis中的日期范围获取数据

Redis排序集排行榜同分排名

java - 当compareto返回0时理解TreeSet