使用比较器根据字典中的键来比较键,SortedDictionary总是抛出异常

问题描述 投票:1回答:1

我想用SortedDictionary实现一个堆,该堆比较值而不是键。我的元素在字典中,我一一添加到SortedDictionary中。它总是在第二次从循环中的“添加”方法发出异常。 “具有相同键的条目已存在”。由于我从字典中获取元素,因此我知道键不能相同。我该怎么做才能完成SortedDictionary的工作?非常感谢!

dic = new Dictionary<int, int>();
var sort = new SortedDictionary<int, int>(Comparer<int>.Create((x, y) => dic[x].CompareTo(dic[y])));
foreach (var pair in dic)
{
    sort.Add(pair.Key, pair.Value);
}
c# sortedlist sorteddictionary
1个回答
0
投票

您可以尝试下一种方法:

var sort = new SortedDictionary<int, int>(
    Comparer<int>.Create(
        (x, y) => 
        {
            int vx = dic[x];
            int vy = dic[y];

            // If values are the same then compare keys.
            if (vx == vy)
                return x.CompareTo(y);

            // Otherwise - compare values.
            return vx.CompareTo(vy);
        }));

如果使用此方法声明sort,则Keys中的sort中的Values将排序。 complete sample显示了此方法的工作原理。


@@ SylvainLIU询问:

在我的原始帖子中,使用dic [x] .CompareTo(dic [y])我的意思是获取Compare()方法,但不要将dic [x]或dic [y]用作SortedDictionary。为什么要求它们唯一?

您是正确的,您的样本按预期工作。那么为什么它抛出异常?

SortedDictionary必须包含唯一键。通过为Comparer指定SortedDictionary,我们指定了如何对键进行排序以及如何定义新键是否唯一。如果Comparer返回0作为新密钥,则此密钥不是唯一的,并且将引发异常An entry with the same key already exists

[如果我们使用比较器dic[x].CompareTo(dic[y]),则要比较键xy,我们使用它们的值dic[x]dic[y]。例如,让我们有两对(Key=1, Value=3)(Key=2, Value=3)。如果我们使用比较器dic[x].CompareTo(dic[y])进行比较,那么这对键不是唯一的,因为它们是通过它们的值3.CompareTo(3) = 0进行比较的。当然,值12是不同的数字,但是从比较器dic[x].CompareTo(dic[y])的角度来看,它们是相同的。因此,如果使用此比较器,则必须确保该对的值必须唯一以防止重复错误。

如果我们使用下一个比较器

int vx = dic[x];
int vy = dic[y];

// If values are the same then compare keys.
if (vx == vy)
    return x.CompareTo(y);

// Otherwise - compare values.
return vx.CompareTo(vy);

然后dic的值不能唯一,因为该比较器考虑到Values中的dic可以相同,并且在这种情况下,它使用另一种策略对其进行排序并检查唯一性。

© www.soinside.com 2019 - 2024. All rights reserved.