gpt4 book ai didi

c# - PowerCollections - MultiDictionary 'Remove' 在找不到值时删除所有值

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:52 28 4
gpt4 key购买 nike

我正在使用来自 http://powercollections.codeplex.com/ 的 powercollections 库

第一个测试通过,但第二个测试失败。如果找不到值,我不希望 Remove 从字典中删除所有项目。

这是个问题还是我误解了 Remove 的功能?

[Test]
public void passing_test()
{
var classes = new MultiDictionary<string, object>(false);
classes.Add("class", "class_name1");
classes.Add("class", "class_name2");
classes.Remove("class", "class_name2");

Assert.AreEqual(1, classes.Count);
}

[Test]
public void failing_test()
{
var classes = new MultiDictionary<string, object>(false);
classes.Add("class", "class_name1");
classes.Remove("class", "class_name2");

Assert.AreEqual(1, classes.Count);
}

最佳答案

它实际上看起来像是代码中的错误:

        /// <summary>
/// Removes a given value from the values associated with a key. If the
/// last value is removed from a key, the key is removed also.
/// </summary>
/// <param name="key">A key to remove a value from.</param>
/// <param name="value">The value to remove.</param>
/// <returns>True if <paramref name="value"/> was associated with <paramref name="key"/> (and was
/// therefore removed). False if <paramref name="value"/> was not associated with <paramref name="key"/>.</returns>
public sealed override bool Remove(TKey key, TValue value)
{
KeyAndValues keyValues = new KeyAndValues(key);
KeyAndValues existing;

if (hash.Find(keyValues, false, out existing)) {
// There is an item in the hash table equal to this key. Find the value.
int existingCount = existing.Count;
int valueHash = Util.GetHashCode(value, valueEqualityComparer);
int indexFound = -1;
for (int i = 0; i < existingCount; ++i) {
if (Util.GetHashCode(existing.Values[i], valueEqualityComparer) == valueHash &&
valueEqualityComparer.Equals(existing.Values[i], value))
{
// Found an equal existing value
indexFound = i;
}
}

if (existingCount == 1) {
// Removing the last value. Remove the key.
hash.Delete(existing, out keyValues);
return true;
}

请注意他们是如何检查 existingCount == 1 的?尽管您输入的值不同,但没有代码检查在 hash.Delete 调用之前的搜索中是否找到索引。解决此问题的正确方法是执行以下操作:

            if (existingCount == 1 && indexFound != -1) {
// Removing the last value. Remove the key.
hash.Delete(existing, out keyValues);
return true;
}

这是完整的来源:http://powercollections.codeplex.com/SourceControl/changeset/view/6259#71508

关于c# - PowerCollections - MultiDictionary 'Remove' 在找不到值时删除所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5986253/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com