您需要實現自定義相等比較和使用DISTINCT方法。
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;
}
}
你不能在字典中主要添加項目'4'了!順便說一句,你知道什麼(A,B)是程序如何理解什麼是A?它可以是(4,3)以及正確的?這裏 –
奉勸小心,因爲字典不一定保留插入順序。如果在添加(3,4)之前添加(4,3),您會期望得到不同的輸出嗎? – Softerware
@Softerware:沒有,沒問題,順序並不重要。 – Pollitzer