C#中的Java TreeMap相当于什么?

25

大多数我咨询的地方都建议使用SortedList,但问题是我正在移植的程序实际上使用了重复的键(通过顺序区分),这在TreeMap中是允许的,但不适用于SortedList。

有什么建议吗?

4个回答

22

4
SortedDictionary不能使用,因为它在有重复键时会抛出ArgumentException异常。正如原帖所说,存在重复的键。 - eugen_nw
2
只需使用SortedDictionary<of TKey, of TValue>.Item[TKey] 属性设置器,如果键已经存在于树中,则替换其值。 - Leonid Vasilev
@Leonid Vasilev:这也不行,因为这样字典里就会缺少一个项目,可能会导致故障。例如,当我将https://github.com/matsim-up/freight-sa/blob/master/src/main/java/org/matsim/up/freight/clustering/containers/ConcaveHull.java翻译成C#时,就发生了这种情况。 - Stefan Steiger

4

1

0

通常使用排序集合

public class ItemComparer : IComparer<int[]>
{
    public int Compare(int[] item1, int[] item2)
    {
        if (item1[0] != item2[0]) return item1[0].CompareTo(item2[0]);
        return item1[1].CompareTo(item2[1]);
    }
}
var s = new SortedSet<int[]>(new ItemComparer());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接