删除所有开关字典对



我有一个 Dictionary,想要 LINQ -emove所有对(b,a)如果有一对(a,b)。

Dictionary<int, int> dictionary = new Dictionary<int, int>();
dictionary.Add(1, 2);
dictionary.Add(3, 4); // keep it
dictionary.Add(4, 3); // remove it
//dictionary.Add(4, 3); // remove it (ignore this impossible line, @Rahul Singh is right)

您需要实现自定义平等比较并使用独特的方法。

Dictionary<int, int> dictionary = new Dictionary<int, int>();
dictionary.Add(1, 2);
 dictionary.Add(3, 4);
dictionary.Add(4, 3);
var result = dictionary.Distinct(new KeyValuePairEqualityComparer()).ToDictionary(x => x.Key, x => x.Value);
    }

平等比较定义为

private class KeyValuePairEqualityComparer : IEqualityComparer<KeyValuePair<int, int>>
{
    public bool Equals(KeyValuePair<int, int> x, KeyValuePair<int, int> y)
    {
        return x.Key == y.Value && x.Value == y.Key;
    }
    public int GetHashCode(KeyValuePair<int, int> obj)
    {
        // Equality check happens on HashCodes first.
        // Multiplying key/value pairs, ensures that mirrors
        // are forced to check for equality via the Equals method
        return obj.Key * obj.Value;
    }
}

幼稚的方法就是根据需要过滤它们。

dictionary = dictionary
.Where( kvp => !(dictionary.ContainsKey(kvp.Value) && dictionary[kvp.Value]==kvp.Key) )
.ToDictionary( kvp => kvp.Key, kvp => kvp.Value )`

让您的对是(1,2),因为从字典中删除此对,您不必为该值而打扰,因为键是唯一的。因此,您可以使用以下代码删除:dictionary.Remove(pair.Key);

但是,如果在集合中找不到指定的密钥,则有机会使用KeyNotFoundException。因此,在继续删除之前,最好检查一下:

int value;
if (dictionary.TryGetValue(pair.Key, out value))
{
   dictionary.Remove(pair.Key);
}

最新更新